简体   繁体   中英

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?

Only the first list shows? Why is this?

To group on the COUNT() aggregation , you'll want to use 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. Instead: LEFT OUTER JOIN lists ON lists.id =leads.list

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