简体   繁体   中英

SQL LEFT JOIN COUNT

Been pounding my head with this one.

I have two tables

employee

  • id
  • name
  • active
  • user_id

report

  • id
  • employee_id
  • user_id
  • created_at
  • and a lot more

I want to select employees which have a specific user_id and furthermore add a column with the count of reports for that specific employee (employee_id) for a specific year.

Here's what i have tried, but failed to succeed.

SELECT c.id, c.name, c.active, c.user_id, COUNT( u.id ) no_of_reports
FROM employee c
LEFT JOIN report u ON c.id = u.employee_id
WHERE c.user_id =1
AND YEAR( u.created_at ) =  '2014'
GROUP BY c.id, c.name
ORDER BY c.name ASC 

Everything works fine, except when i put in a condition for my LEFT JOIN. I only want it to count the u.id if the created_at column is within the year 2014. That works fine, BUT if there are NO u.ids (meaning there are no reports for that employee), the whole employee is left out, instead of just setting the no_of_reports to 0, and still give me the id, name, active and user_id as a row in my result.

Removing AND YEAR(u.created_at)='2014' gives me the correct result, except it includes the reports created outside 2014.

You can put multiple conditions in your JOIN clause:

SELECT c.id, c.name, c.active, c.user_id, COUNT( u.id ) no_of_reports
FROM employee c
LEFT JOIN report u ON (c.id = u.employee_id AND YEAR( u.created_at ) =  '2014')
WHERE c.user_id =1
GROUP BY c.id, c.name
ORDER BY c.name ASC 

This will select all users, but only join the reports created in 2014

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