Ronaldinho Learn Coding
Ronaldinho Learn Coding

Reputation: 13824

COUNT function and INNER JOIN on multiple tables

This is so complicated (for me) because I usually only work with single table and simple queries (SELECT, INSERT, UPDATE), but now I am in a situation where I am stuck.

enter image description here

enter image description here

enter image description here

I tried this query but it not worked, it seems to display all columns right but the COUNT pending files column (assume the manager_id = 11)

SELECT COUNT(file_id) as 'Pending files', projects.project_id, projects.project_name, projects.status, projects.start_date
FROM ((project_manager 
INNER JOIN files 
ON project_manager.mag_id = files.manager_id AND project_manager.mag_id = 11 AND file_status = 'Pending')
INNER JOIN projects
ON projects.project_id = project_manager.project_id)
GROUP BY projects.project_id, projects.project_name, projects.status, projects.start_date
ORDER BY projects.status, projects.start_date DESC

enter image description here

I need help with a correct query and if you can explain it a little bit that would be much appreciated!

Upvotes: 0

Views: 4992

Answers (1)

TMNT2014
TMNT2014

Reputation: 2130

You need to include project_id in your Join to the files table and use a left join -

SELECT COUNT(file_id) as 'Pending files', projects.project_id, projects.project_name, projects.status, projects.start_date

FROM ((project_manager 
LEFT JOIN files 
ON project_manager.mag_id = files.manager_id AND project_manager.mag_id = 11 AND file_status = 'Pending' AND project_manager.project_Id = files.project_id )
INNER JOIN projects
ON projects.project_id = project_manager.project_id)

WHERE project_manager.mag_id = 11
GROUP BY projects.project_id, projects.project_name, projects.status, projects.start_date
ORDER BY projects.status, projects.start_date DESC

Upvotes: 1

Related Questions