2012-01-08 65 views
2

編寫查詢以顯示由同一位醫生治療的不同患者對。
下表是存在的:根據連接中的某些條件顯示對的查詢

doctor: 
d_id 
d_name 

patient: 
p_id 
p_name 

treatment: 
d_id 
p_id 
disease 
medicine 

查詢:

Select p1.p_name, p2.p_name 
from patient p1, patient p2, treatment t1, treatment t2 
where t1.d_id=t2.d_id 
AND t1.p_id<>t2.p_id 
AND t1.p_id=p2.p_id 
AND t2.p_id=p1.p_id; 

您能否提供一個更好的/替代查詢(甲骨文的風格),消除了重複對[像(P1,P6)和( P6,P1)?

+1

明顯的對稱性破壞條件是「p1.p_id wildplasser 2012-01-08 11:12:36

+0

任何其他方法....?另外,@Andomar,這種情況的起源是什麼。看起來更像是一種舌尖的解決方案......拼湊而成。 – 2012-01-08 11:44:59

回答

4

要搜索由同一位醫生治療的所有其他患者,請自行加入治療表。您可以使用distinct刪除重複:

SELECT distinct p1.Name 
,  p2.Name 
FROM  patient p1 
JOIN  treatment t1 
ON  p1.id = t1.p_id 
JOIN  treatment t2 
ON  t1.d_id = t2.d_id -- Same doctor 
     and t1.p_id < p2.p_id -- Higher patient nr 
JOIN  patient p2 
ON  p2.id = t2.p_id 

條件t1.p_id < p2.p_id消除另一種重複的,有交換的患者。 John, Mary將與Mary, Join相同。其中的一個將被<條件過濾掉。

0

這將retun由同一個醫生

trated患者名單從治療選擇不同patient.p_name,treatment.p_id,treatment.d_id通過treatment.d_id

上treatment.p_id = patient.p_id組內加入病人
相關問題