我正在尝试使用以下详细信息编写一个mysql查询 -
我有三张桌子
1)预订表,其中包含列booking_id,journey_start_datetime,journey_end_datetime。
2)驱动程序表,列驱动程序为driver_id,driver_name。
3)Driver_Assign表,其中包含列booking_id,driver_id,busy_start_datetime,busy_end_datetime。
当我向司机分配预订时,新条目会转到Driver_Assign表格,其中包含booking_id,journey_start_datetime,journey_end_datetime的详细信息。
我希望得到所有在一段时间内都不忙的车手名字。即
让一个预订分配给司机" John" for journey_start_datetime->' 2014-06-27 12:00:00'和journey_end_datetime->' 2014-06-27 14:00:00'。
现在进行新预订(journey_start_datetime->' 2014-06-27 13:00:00'和journey_end_datetime->' 2014-06-27 15:00:00&#39 ;)司机约翰不会来。
将OP的代码从评论转移到问题 -
SELECT U.driver_name
FROM driver AS U
where U.id not in
(select driver_id
from driver_assign as DVA
WHERE ('2014-06-27 13:00:00'>= DVA.busy_start_datetime OR
'2014-06-27 13:00:00'<= DVA.busy_end_datetime
) AND
('2014-06-27 15:00:00'>= DVA.busy_start_datetime OR
'2014-06-27 15:00:00'=< DVA.busy_end_datetime
)
)
答案 0 :(得分:0)
SELECT d.driver_name
FROM driver d
LEFT JOIN driver_assign da ON da.driver_id=d.driver_id
WHERE
da.busy_start_datetime <='2014-06-27 13:00:00'
AND da.busy_end_datetime>='2014-06-27 13:00:00'
HAVING da.driver_id is null
您只需要LEFT JOIN并排除非空(忙)的行
答案 1 :(得分:0)
SELECT d.driver_name
FROM driver d
WHERE d.driver_id not in
(SELECT driver_id from driver_assign
WHERE
(busy_start_datetime >= '2014-06-27 13:00:00' AND NOT busy_start_datetime >= '2014-06-27 15:00:00')
OR
(busy_end_datetime > '2014-06-27 13:00:00' AND NOT busy_end_datetime > '2014-06-27 15:00:00'
)
OR (busy_start_datetime < '2014-06-27 13:00:00' AND busy_end_datetime > '2014-06-27 15:00:00')
)