我有三张桌子(医生,clinic_doctor_timings,hosptial_doctor_timings)。两个时间表都包含医生表的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')
我需要让诊所和医院为医生提供给定时间,而不依赖于诊所和医院。
答案 0 :(得分: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';
让去诊所的医生 OR 医院
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;
这不足以得到你想要的东西吗?