2013-05-02 99 views
0

我有三張表(doctor,clinic_doctor_timings,hosptial_doctor_timings)。時間表中包含醫生表的ID作爲外鍵,還存儲醫生的時間和時間。現在我需要選擇在給定時間內去往診所或醫院的醫生ID,即從和到。將兩個表與mysql中的一組條件結合起來

我寫了一個查詢,可用於診所或醫院,但不是兩者兼而有之。

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

我還是不明白你想要什麼.... – mjb 2013-05-02 12:33:21

回答

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; 

這還不夠得到你想要的嗎?

+0

居然沒有。第三個查詢沒有得到我期望的結果。它只會給診所和醫院帶來共同的結果。不過謝謝。我找到了找到它的方法。 – John 2013-05-03 05:39:06

+0

@泰米爾我還是不明白你想要什麼。因爲你的描述不清楚。我只是猜你想要什麼。 – mjb 2013-05-04 09:20:17

+0

@泰米爾好的,我寫了第4個查詢。在我的問題中更新。 – mjb 2013-05-04 09:29:27

相關問題