2012-10-12 105 views
0

我有以下加入語句:SQL加入,消除重複的結果

SELECT DISTINCT dn.fname, dn.lname,w.websit,q.qual,q.year,q.postqual,p.pnumber,a.accred,n.nspecial 
FROM cur_doctor_names dn 
LEFT JOIN cur_website w ON dn.userid = w.userid 
LEFT JOIN cur_qualification q ON dn.userid = q.userid 
LEFT JOIN (Select * from cur_phone_numbers where type="primary") p On dn.userid = p.userid 
Left JOIN cur_accreditation a On dn.userid = a.userid 
Left JOIN cur_niche n On dn.userid = n.userid 
WHERE dn.userid =69 
GROUP BY p.pnumber 

對於表cur_phone_numbers(P),cur_accreditation(一),cur_niche(n)的結果可以從0到3記錄一個包含用戶,我目前得到的結果給了我所有可能的數據組合。我試着在列上單獨使用group by,但是這消除了其他列的結果。我不介意用空值得到結果。這是我目前得到的結果是:

fname   lname  website qual year postqual pnumber accred nspecial 
=========================================================================================== 
First Doctor Last Doctor NULL  NULL NULL NULL  123  ISO 9001 one 
First Doctor Last Doctor NULL  NULL NULL NULL  123  ISO 9001 two 
First Doctor Last Doctor NULL  NULL NULL NULL  123  ISO  one 
First Doctor Last Doctor NULL  NULL NULL NULL  123  ISO  two 
First Doctor Last Doctor NULL  NULL NULL NULL  1234  ISO 9001 one 
First Doctor Last Doctor NULL  NULL NULL NULL  1234  ISO 9001 two 
First Doctor Last Doctor NULL  NULL NULL NULL  1234  ISO  one 
First Doctor Last Doctor NULL  NULL NULL NULL  1234  ISO  two 
+0

根據您所提供的數據,它不重複的數據。最後3列'pnumber','accred','nspecial'顯示每行不同的值。如果你只想要一個值,那麼你需要決定你想要返回哪一個。 – Taryn

回答

1

你必須選擇使用aggregate functions的價值之一,例如max

SELECT dn.fname, dn.lname,w.websit,q.qual,q.year,q.postqual,max(p.pnumber),max(a.accred),max(n.nspecial) 
FROM cur_doctor_names dn 
LEFT JOIN cur_website w ON dn.userid = w.userid 
LEFT JOIN cur_qualification q ON dn.userid = q.userid 
LEFT JOIN (Select * from cur_phone_numbers where type="primary") p On dn.userid = p.userid 
Left JOIN cur_accreditation a On dn.userid = a.userid 
Left JOIN cur_niche n On dn.userid = n.userid 
WHERE dn.userid =69 
GROUP BY p.pnumber