Matthew
Matthew

Reputation: 7725

COUNT(*) and LEFT JOIN

This query:

SELECT staff.staff_id, COUNT(references_table.staff_id) 
FROM staff 
LEFT JOIN references_table USING (staff_id)

returns this:

staff_id    COUNT(references_table.staff_id)
1            2

How can I get it to return 0 as the count for staff_ids that don't have any references?

Upvotes: 1

Views: 591

Answers (2)

John Douthat
John Douthat

Reputation: 41179

a GROUP BY clause will do the trick

SELECT staff.staff_id, COUNT(references_table.staff_id) 
FROM staff 
LEFT JOIN references_table USING (staff_id)
GROUP BY staff.staff_id

Upvotes: 5

ChrisLively
ChrisLively

Reputation: 88064

Try a left outer join.

Upvotes: 1

Related Questions