从两个表中选择左连接计数的计数

时间:2015-09-30 15:38:08

标签: mysql select count left-join

我有以下查询:

select count(*) as `count`, ass.date_assigned as date_assigned
from `buyers` as b
left join `assignments` as ass on (ass.id_buyer = b.id)

我只想要计算总数buyers。问题是它似乎也在计算所有assignments

我已尝试按b.idass.id_buyer分组,我们已尝试将count(*)更改为count(b.id)

没有任何作用。如何解决此问题,以便仅计算buyers

2 个答案:

答案 0 :(得分:2)

使用COUNT(DISTINCT)

SELECT COUNT(DISTINCT b.id) AS count, MAX(a.date_assigned) AS last_date_assigned
FROM buyers AS b
INNER JOIN assignments AS a ON a.id_buyer = b.id

我也从LEFT JOIN更改为INNER JOIN,因此它只会计算有作业的买家(否则为什么要加入assignments?)。并使用MAX(a.date_assigned)以便选择特定的分配日期,而不仅仅是来自任何分配的随机日期。

答案 1 :(得分:0)

使用正确的外部加入:

select count(*) as `count`, ass.date_assigned as date_assigned from `buyers` as b right outer join `assignments` as ass on (ass.id_buyer = b.id)