简体   繁体   English

从两个表中选择带有左联接计数的计数

[英]Select count with left join counting from both tables

I have the following query: 我有以下查询:

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)

I only want this to count the total buyers . 我只想以此来计算buyers总数。 The problem is it appears to be counting all of the assignments as well. 问题在于它似乎也在计算所有assignments

I've tried grouping by b.id and ass.id_buyer , I've tried changing count(*) to count(b.id) . 我试过按b.idass.id_buyer分组,我试过将count(*)更改为count(b.id)

Nothing works. 没用。 How do I fix this so it only counts the buyers ? 我该如何解决,这样才算buyers

Use COUNT(DISTINCT) : 使用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

I've also changed from LEFT JOIN to INNER JOIN so that it will only count buyers who have assignments (otherwise why join with assignments ?). 我也从改变LEFT JOININNER JOIN ,这样只会算买家谁拥有分配(否则为什么有参加assignments ?)。 And used MAX(a.date_assigned) so that it selects a particular assignment date, not just a random date from any of the assignments. 并使用MAX(a.date_assigned)以便它选择特定的分配日期,而不仅仅是从任何分配中选择随机日期。

使用权外加入:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM