/ / ľavé spojenie problém s mysql - php, mysql, sql

ľavý spojiť problém s mysql - php, mysql, sql

Mám dve tabuľky a snaží sa pripojiť oboch z nich na základe primárneho a cudzieho key.But problém je, že v druhej tabuľke cudzí kľúč má viac duplicitných riadkov.

Štruktúra: -

1 Tabuľka - kategória

catid   catname
1       AAA
2       BBB
3       CCC

2 Tabuľka - odpovede

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

Výsledok by mal byť

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

Moja otázka je

    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

Ale to nie je vracanie výsledkov, čo chcem. Vracia len jeden riadok, ktorý je

userid    catid   catname   present in answers table
6          2         BBB       yes

odpovede:

3 pre odpoveď č. 1

Myslím, že musíte zmeniť poradie pripojení, takže si všetko ponecháte category a potom posuňte where podmienkou on doložka:

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;

Všimnite si, že som tiež zmenil sum() na a count() -- count() automaticky spočíta, koľkokrát argument nie je NULL.