[英]LEFT OUTER JOIN with count()?
Consider these tables: 考虑以下表:
lists : 清单 :
id name
1 somename
2 someothername
leads : 潜在客户 :
id list
1 1
2 1
3 1
I currently have following query: 我目前有以下查询:
SELECT lists.*, count(leads.id)
FROM lists
LEFT OUTER JOIN leads ON lists.id =leads.list
Why is only the first list showing, instead of showing both? 为什么只显示第一个列表,而不同时显示两个列表? List 1, and count = 3, and list 2 with count = 0?
列表1,计数= 3,列表2计数= 0?
Only the first list shows? 仅显示第一个列表? Why is this?
为什么是这样?
To group on the COUNT()
aggregation , you'll want to use GROUP BY
: 要对
COUNT()
聚合进行分组,您需要使用GROUP BY
:
SELECT
lists.id, count(leads.id)
FROM
lists
LEFT OUTER JOIN leads
ON lists.id =leads.list
GROUP BY
lists.id
You are Left Joining from leads
to lists
, which selects all values from leads
(Which only has List 1) and only values from lists
where there is a match. 您是从
leads
到lists
左连接,它将从leads
选择所有值(只有列表1),并且仅从匹配的lists
中选择值。 Instead: LEFT OUTER JOIN lists ON lists.id =leads.list
而是:
LEFT OUTER JOIN lists ON lists.id =leads.list
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.