Thi*_*ira 6 php mysql sql laravel laravel-5
我无法创建一个选择查询,该查询将检索游戏中不存在的所有用户ID以及日期之间的可用性.
示例:检索不在日期2017-08-10和之间的所有用户2017-08-12.
得到 [3 , 4, 5]
用户
| Id | Name |
| 1 | Jonh |
| 2 | Mark |
| 3 | Caroline |
| 4 | David |
| 5 | George |
Run Code Online (Sandbox Code Playgroud)
游戏
| Id | User_Id | Start_Date | End_Date |
| 1 | 1 | 2017-06-01 | 2017-06-01 |
| 2 | 1 | 2017-08-12 | 2017-08-13 |
| 3 | 4 | 2017-08-13 | 2017-08-14 |
Run Code Online (Sandbox Code Playgroud)
可用性
| Id | User_Id | Start_Date | End_Date |
| 1 | 1 | 2017-05-01 | 2017-05-25 |
| 1 | 2 | 2017-08-10 | 2017-08-17 |
| 1 | 3 | 2017-06-20 | 2017-07-10 |
Run Code Online (Sandbox Code Playgroud)
我正在使用Laravel 5.4,但如果答案是Raw或Eloquent,我会很高兴的.
在 SQL 中,您可以使用NOT EXISTS:
select *
from users u
where not exists (
select 1
from games g
where u.id = g.user_id
and (
g.start_date between '2017-08-10' and '2017-08-12'
or g.end_date between '2017-08-10' and '2017-08-12'
)
)
and not exists (
select 1
from Availability a
where u.id = a.user_id
and (
a.start_date between '2017-08-10' and '2017-08-12'
or a.end_date between '2017-08-10' and '2017-08-12'
)
);
Run Code Online (Sandbox Code Playgroud)
另一种使用方法LEFT JOIN是:
select distinct u.*
from t_users u
left join games g on u.id = g.user_id
and (g.start_date between '2017-08-10' and '2017-08-12'
or g.end_date between '2017-08-10' and '2017-08-12')
left join availability a on u.id = a.user_id
and (a.start_date between '2017-08-10' and '2017-08-12'
or a.end_date between '2017-08-10' and '2017-08-12')
where g.user_id is null and a.user_id is null;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
72 次 |
| 最近记录: |