簡體   English   中英

MySQL從表1中選擇ID並從表2中選擇計數(ID)

[英]Mysql select id from table1 and select count(id) from table2

我有兩張桌子。 我想從表1中選擇ID,並從表2中進行計數

表格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

表2

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

我嘗試了以下查詢,因為表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

但是我需要所有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

首先,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

小提琴演示

樣本數據集更新后進行編輯

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

小提琴演示2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM