mysql 来自 table1 的结果,其中 table2 不匹配并且在 start_datetime 和 start_datetime + 8 小时之间

mysql result from table1 where table2 doesn't match AND between start_datetime and start_datetime + 8 hours

我想查询来自 table employees 的员工 ID 列表,但排除已经在名为 employee_schedule 的单独 table 中的员工 ID,如果它介于特定的 datetime 和相同的 datetime + 8 hours 之间。由于其他原因,我没有使用 datetime 作为轮班结束时间。

SELECT user_id
FROM employees AS t1
LEFT OUTER JOIN employee_schedule AS t2 ON t1.user_id = t2.assigned_guard_id
WHERE t2.assigned_guard_id IS NULL
AND ('2017-10-23 18:00:00' BETWEEN t2.shift_start 
AND ADDTIME(t2.shift_start, '12:00:00'))

结果:

`employees` |  `employee_schedule`
----------------------------------------------------------------------------------------
id          |  guard_assigned_id, shift_start(datetime), shift_duration(INT, minutes)
----------------------------------------------------------------------------------------
17          |  17, '2017-10-23 18:00:00', '480'
19          |  
22          |
----------------------------------------------------------------------------------------

结果应该只显示 1922,因为 17 出现在 shift_startshift_start + shift_duration 之间的时间表中。

我的查询返回 0 个结果。

您的范围条件正在将 LEFT JOIN 转换为 INNER JOIN。对于同一行,这两个条件永远不会成立。您需要将第二个条件移动到 LEFT JOIN 的 ON 子句。所以应该是:

SELECT user_id
FROM employees AS t1
LEFT OUTER JOIN employee_schedule AS t2
    ON  t1.user_id = t2.assigned_guard_id
    AND '2017-10-23 18:00:00' BETWEEN t2.shift_start
        AND ADDTIME(t2.shift_start, '12:00:00')
WHERE t2.assigned_guard_id IS NULL

请注意,引擎可能无法优化范围条件以使用索引。最好写成

AND t2.shift_start <= '2017-10-23 18:00:00'
AND t2.shift_start >= SUBTIME('2017-10-23 18:00:00', '12:00:00')

AND t2.shift_start BETWEEN SUBTIME('2017-10-23 18:00:00', '12:00:00')
    AND '2017-10-23 18:00:00'

如果想用shift_duration代替常数时间,可以用

AND t2.shift_start <= '2017-10-23 18:00:00'
AND t2.shift_start >= '2017-10-23 18:00:00' - INTERVAL shift_duration MINUTE