[英]Mysql select id from table1 and select count(id) from table2
I have two tables. 我有两张桌子。 I want to select id from table 1 and count the same from table2
我想从表1中选择ID,并从表2中进行计数
Table 1 表格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 表2
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. 我尝试了以下查询,因为表2中没有3和4,所以仅输出ansId 1和2。
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. 但是我需要所有ansId 1,2,3,4,其3和4的计数为0,如下所示。
Id opt COUNT(b.ansId)
1 Chris Christie 1
2 Hillary Clinton 1
3 Allan West 0
4 Joe Biden 0
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 ie 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 首先,group by缺少您的内容,count是一个聚合函数,需要将其分组,其次,您需要在on子句(即
and a.qId =30
使用带有附加条件的左and a.qId =30
因此它将stil给您结果如果在右表中未找到左ID,则使用where子句将筛选出整个结果集,而如果在联接中使用其他条件,则将仅从右表中筛选记录
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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.