一个查询中有多个SELECT

时间:2014-06-17 15:53:39

标签: sql select union

我使用的是3个表:项目 project_manager project_employee

项目

 - project_id (int, PK)
 - project_name

project_manager

 - project_id  (int, PK)
 - manager_id  (int, PK)

project_employee

 - project_id  (int, PK)
 - employee_id  (int, PK)

假设管理员当前已登录(因此我们知道他的ID是什么),我尝试做的是编写一个显示网格视图的查询:

project_id,project_name和项目中的员工数量,

例如:

Project ID              Project Name                  Number of employees
     1                  Test Project                           3
     2                  Government Fund                        5

所以我试过了:

SELECT COUNT (*) AS employee_number, NULL AS Unnecessary_Column
FROM [project_employee] 
WHERE project_id = @pID
UNION 
SELECT [projects].project_id, [projects].project_name 
FROM [projects], [project_manager] 
WHERE [project_manager].project_id = [projects].project_id AND [project_manager].mag_id = @mID

但结果并不像我期望的那样...我的查询得到的是2栏employee_number和Unnecessary_Column,其中包含混乱的数据。

1 个答案:

答案 0 :(得分:1)

尝试此查询

SELECT           projects.project_id,
                 projects.project_name,
                 count(*) as NumberOfEmployees
FROM             projects
INNER JOIN       project_manager manager ON projects.project_id = manager.project_id 
INNER JOIN       project_employee emp ON projects.project_id = emp.project_id  
WHERE            manager.manager_id = @mId            
GROUP BY         projects.project_id,projects.project_name