多个表上的COUNT函数和INNER JOIN

时间:2014-06-23 20:47:58

标签: sql sql-server count

这对我来说太复杂了,因为我通常只使用单表和简单查询(SELECT,INSERT,UPDATE),但现在我处于被卡住的状态。

  • 我想要存档的是:当项目经理登录他/她的帐户时,网格视图会显示他/她所有项目的快速概览(ID,创建日期,名称和数量)文件处于待处理状态)如下图:

enter image description here

  • 将涉及3个表:

enter image description here

  • manager_id = 11的示例数据:

enter image description here

我尝试了这个查询但是没有用,它似乎显示所有列正确但COUNT挂起文件列(假设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

我需要有关正确查询的帮助,如果您能解释一下,我将非常感激!

1 个答案:

答案 0 :(得分:1)

您需要在Join to the files表中包含project_id并使用左连接 -

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