SQL Join,消除重复结果

时间:2012-10-12 10:12:51

标签: sql join

我有以下加入声明:

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(a),cur_niche(n)结果可以包含0到3个用户的记录,我当前获得的结果为我提供了数据的所有可能组合。我尝试在列上单独使用group by,但这会消除其他列的结果。我不介意用nulls得到一个结果。这是我目前得到的结果:

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

1 个答案:

答案 0 :(得分: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