0

我有三张桌子(医生、诊所医生计时、医院医生计时)。两个时间表都包含医生表的 id 作为外键,它还存储医生的从和到时间。现在我需要选择在给定时间去诊所或医院的医生 ID,即往返。

我写了一个查询,它适用于诊所或医院,但不能同时适用。

SELECT 
DISTINCT
SQL_CALC_FOUND_ROWS
`doctor`.`id`,
`doctor`.`name`
FROM
`doctor`
JOIN clinic_doctor_timings AS cl
ON cl.doctor_id = doctor.id
WHERE
TIME_FORMAT(`cl`.`from`, %h:%i %p) >= '05:00 AM'
AND TIME_FORMAT(`cl`.`to`, %h:%i %p) >= '10:00 PM'

上面的查询工作正常,但是在我想结合 Clinic_doctor_timings 和 hospital_doctor_timings 表之后,我没有得到我期望的结果。

.........
JOIN clinic_doctor_timings AS cl
ON cl.doctor_id = doctor.id
JOIN hospital_doctor_timings AS hs
ON hs.doctor_id = doctor.id
WHERE
(TIME_FORMAT(`cl`.`from`, %h:%i %p) >= '05:00 AM'
AND TIME_FORMAT(`cl`.`to`, %h:%i %p) <= '10:00 PM')
XOR
(TIME_FORMAT(`hs`.`from`, %h:%i %p) >= '05:00 AM'
AND TIME_FORMAT(`hs`.`to`, %h:%i %p) <= '10:00 PM')

我需要在独立于诊所和医院的给定时间为医生安排诊所和医院。

4

1 回答 1

0

找去诊所的医生:

SELECT a.id, a.name FROM doctor a 
INNER JOIN clinic_doctor_timings b ON a.id = b.doctor_id
WHERE 
b.`from` >= '2013-05-02 05:00:00' AND
b.`to` <= '2013-05-02 22:00:00';

找去医院的医生:

SELECT a.id, a.name FROM doctor a 
INNER JOIN hospital_doctor_timings b ON a.id = b.doctor_id
WHERE 
b.`from` >= '2013-05-02 05:00:00' AND
b.`to` <= '2013-05-02 22:00:00';

找去诊所和医院的医生

SELECT a.id, a.name FROM doctor a 
INNER JOIN clinic_doctor_timings b ON a.id = b.doctor_id
INNER JOIN hospital_doctor_timings c ON a.id = c.doctor_id
WHERE 
b.`from` >= '2013-05-02 05:00:00' AND
b.`to` <= '2013-05-02 22:00:00' AND
c.`from` >= '2013-05-02 05:00:00' AND
c.`to` <= '2013-05-02 22:00:00';

找去诊所医院的医生

SELECT a.id, a.name FROM doctor a 
WHERE
(
    SELECT COUNT(b.id) FROM clinic_doctor_timings b WHERE
    b.doctor_id = a.id and
    b.`from` >= '2013-05-02 05:00:00' AND
    b.`to` <= '2013-05-02 22:00:00'
) > 0
or
(
    SELECT COUNT(c.id) FROM hospital_doctor_timings c WHERE
    c.doctor_id = a.id and
    c.`from` >= '2013-05-02 05:00:00' AND
    c.`to` <= '2013-05-02 22:00:00'
) > 0;

这还不足以得到你想要的吗?

于 2013-05-02T12:39:01.253 回答