Ho due tabelle e provo ad unirle entrambe basandomi su chiave primaria ed esterna. Ma il problema è che nella seconda tabella la chiave esterna ha più righe duplicate.
Struttura :-
1 tabella - categoria
catid catname
1 AAA
2 BBB
3 CCC
2 Tabella - risposte
ansid catid userid
1 1 9
2 1 9
3 2 9
4 2 6
Il risultato dovrebbe essere
userid catid catname present in answers table
null 1 AAA no
6 2 BBB yes
null 3 CCC no
La mia domanda è
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
Ma non restituisce i risultati ciò che voglio. Restituisce solo una riga
userid catid catname present in answers table
6 2 BBB yes
risposte:
3 per risposta № 1Penso che sia necessario cambiare l'ordine dei join, in modo da mantenere tutto nel category
tabella e quindi spostare il where
condizione al on
clausola:
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;
Nota che ho anche cambiato il sum()
a a count()
-- count()
conta automaticamente il numero di volte in cui l'argomento non è NULL
.