从左连接表中按计数分组

时间:2011-12-14 01:21:04

标签: mysql count group-by

这是我的疑问:

$select d.*, 
count(a.id) as delivered
from `dealerships` as d
left join `assignments` as a on (a.id_dealership = d.id)
group by d.id
order by d.name asc

现在这可行,但它正在计算重复的潜在客户。当我将a.id_lead添加到群组中时,它会弄乱一切。 assignments表中有一列名为id_lead,我希望count()(delivered)计算按id_lead分组的分配总数,以便忽略超过1行且具有相同的id_lead

1 个答案:

答案 0 :(得分:1)

这是什么意思? :

select d.*, 
count(distinct a.id_lead) as delivered
from `dealerships` as d
left join `assignments` as a on (a.id_dealership = d.id)
group by d.id
order by d.name asc

它与您的查询相同,只是它不计算a记录的总数,而只计算不同的非空值的数量< / em> in a.id_lead

(如果不是你的意思,那么请澄清。)