简体   繁体   中英

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 . The problem is it appears to be counting all of the assignments as well.

I've tried grouping by b.id and ass.id_buyer , I've tried changing count(*) to count(b.id) .

Nothing works. How do I fix this so it only counts the buyers ?

Use 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 ?). And used MAX(a.date_assigned) so that it selects a particular assignment date, not just a random date from any of the assignments.

使用权外加入:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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