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

时间:2017-12-09 19:55:51

标签: mysql datetime join date-arithmetic

我想查询表employees中的员工ID列表,但如果员工ID位于特定employee_schedule之间且已列在名为datetime的单独表中,则会将其排除在外。那个datetime + 8 hours。由于其他原因,我没有将日期时间用于班次结束。

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结果。

1 个答案:

答案 0 :(得分:0)

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

Title

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

可能会更好
figure(title='new title')

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'