我在创建一个选择查询时遇到问题,该查询将检索不在游戏中的所有用户 ID 和日期之间的可用性。
示例:检索不在日期 2017-08-10
和 2017-08-12
之间的所有用户。
获取 [3 , 4, 5]
用户
| Id | Name |
| 1 | Jonh |
| 2 | Mark |
| 3 | Caroline |
| 4 | David |
| 5 | George |
游戏
| 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 |
可用性
| 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 |
我正在使用 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'
)
);
Demo
另一种使用 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;
Demo
关于php - Mysql Left Join with Group By 和 Between,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43984957/