/ mysql - php, mysql, sql के साथ / लेफ्ट जॉइन इश्यू

mysql - php, mysql, sql के साथ समस्या में शामिल हो गए

मेरे पास दो टेबल हैं और दोनों को प्राथमिक और विदेशी कुंजी के आधार पर जोड़ने की कोशिश कर रहे हैं। लेकिन समस्या यह है कि दूसरी तालिका में विदेशी कुंजी में कई डुप्लिकेट पंक्तियाँ हैं।

संरचना: -

1 टेबल - श्रेणी

catid   catname
1       AAA
2       BBB
3       CCC

2 टेबल - जवाब

ansid    catid     userid
1        1         9
2        1         9
3        2         9
4        2         6

परिणाम होना चाहिए

userid    catid   catname   present in answers table
null       1         AAA       no
6          2         BBB       yes
null       3         CCC       no

मेरी पूछताछ है

    SELECT a.userid, c.catid,c.catname,
case when sum(a.catid is not null) > 0
then "yes" else "no" end as present_in_answers_table
from answers a left join
category c  on c.catid = a.catid
where  (a.userid = 6) group by c.catid

लेकिन यह परिणाम नहीं दे रहा है कि मुझे क्या चाहिए। यह केवल एक पंक्ति देता है

userid    catid   catname   present in answers table
6          2         BBB       yes

उत्तर:

जवाब के लिए 3 № 1

मुझे लगता है कि आपको जोड़ों के क्रम को बदलने की आवश्यकता है, इसलिए आप सब कुछ अंदर रखते हैं category तालिका और फिर स्थानांतरित करें where के लिए शर्त on खंड:

SELECT a.userid, c.catid, c.catname,
(case when count(a.catid) > 0 then "yes" else "no"
end) as present_in_answers_table
from category c left join
answers a
on c.catid = a.catid and
a.userid = 6
group by c.catid;

ध्यान दें कि मैंने भी बदल दिया है sum() ए के लिए count() -- count() स्वचालित रूप से गिना जाता है कि तर्क कितनी बार है NULL.