php - Mysql Left Join with Group By 和 Between

标签 php mysql sql laravel laravel-5

我在创建一个选择查询时遇到问题,该查询将检索不在游戏中的所有用户 ID 和日期之间的可用性。

示例:检索不在日期 2017-08-102017-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/

相关文章:

php - 是否有基于 PHP 的 Python Nose 实现?

php - 获取 1000 个平均值中的 50 个平均值

sql - MySQL:返回具有 50 个 ID 的单个记录,而不是具有单个 ID 的 50 个记录

sql - 关于 Pivot 与 Case 优劣的问题

sql - 在 Informix DB 中选择硬编码值

SQL 全外连接重复问题

php - 取消订阅每月定期付款?

php - mysqli_fetch_assoc()需要参数/调用成员函数bind_param()错误。如何获取并修复实际的mysql错误?

php - 当我从数据库表中选择下拉值时,页面刷新并且值返回到选择选项

mysql - 拉拉维尔 : how to query the result of query scope