Domanda

I have two tables. I want to select id from table 1 and count the same from table2

Table 1

Id  qId opt
1   30  Chris Christie
2   30  Hillary Clinton
3   30  Allan West
4   30  Joe Biden
5   31  Mark
6   31  Ben Johnson

Table2

poll_id qId ansId
201     30  1
202     30  2
204     31  8

The below query i tried, outputs only the ansId 1 and 2 since there is no 3 and 4 in Table2.

SELECT a.Id, 
a.opt, 
COUNT(b.ansId)  
from Table1 a 
INNER JOIN Table2 b ON a.Id = b.ansId 
where a.qId =30

But i need all ansId 1,2,3,4 with count of 3 and 4 as 0 as given below.

Id   opt               COUNT(b.ansId)
1    Chris Christie    1
2    Hillary Clinton   1
3    Allan West        0
4    Joe Biden         0
È stato utile?

Soluzione

First thing your are missing with group by ,count is an aggregate function and this needs to be grouped,second you need to use left join with an additional condition in on clause i.e and a.qId =30 so it will stil gives you the result if left id is not found in right table,using where clause will filter out the whole resultset while if you use additional condition in join this will only filter the records from the right table

SELECT a.Id,
a.opt,
COUNT(b.ansId)  from Table1 a
LEFT JOIN Table2 b ON a.Id = b.ansId and  a.qId =30
GROUP BY a.Id

Fiddle Demo

Edit after sample dataset is updated

SELECT a.Id,
a.opt,
COUNT(b.ansId)  from Table1 a
LEFT JOIN Table2 b ON a.Id = b.ansId
WHERE  a.qId =30
GROUP BY a.Id

Fiddle demo 2

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top