0

在此处输入图像描述

表部门

表部门

表员工

在此处输入图像描述

有一个没有任何员工的运营部门。所以,我相信查询也会检索到行(图 1):

Department_ID=10 , Department_Name =Operations, Employee=0

为什么不发生???

 SELECT EMPLOYEE.Department_ID, DEPARTMENT.Department_Name, Count(*) AS Employees 
FROM EMPLOYEE right JOIN DEPARTMENT ON DEPARTMENT.Department_ID = EMPLOYEE.Department_ID
GROUP BY DEPARTMENT.Department_Name,.EMPLOYEE.Department_ID
4

3 回答 3

1

由于您对此查询关心的主要数据来自 DEPARTMENT 表,因此您可能需要考虑将查询重写为:

SELECT DEPARTMENT.Department_ID, DEPARTMENT.Department_Name, Count(EMPLOYEE.Employee_ID) As Employees 
FROM DEPARTMENT 
LEFT JOIN EMPLOYEE ON EMPLOYEE.Department_ID = DEPARTMENT.Department_ID 
GROUP BY DEPARTMENT.Department_ID, DEPARTMENT.Department_Name
于 2012-12-18T19:07:29.920 回答
1

默认join值为 an inner join,它仅返回在两侧至少找到一行的行。替换joinleft join检索没有员工的部门。

示例代码:

SELECT  e.Department_ID
,       d.Department_Name
,       count(e.Employee_ID) AS Employees 
FROM    Department d
LEFT JOIN
        Employee e
ON      d.Department_ID = e.Department_ID
GROUP BY 
        d.Department_ID
,       d.Department_Name
于 2012-12-18T19:01:56.150 回答
1

这应该可以解决问题。如果您先有表,您可以输入a ,但这不好的原因是因为很快您的查询将开始混合和连接,这变得非常难以阅读,即使对于经验丰富的 SQL 专业人员也是如此。通过坚持与您保持查询的可维护性和可理解性。(在极少数情况下,可能会简化具有复杂优先顺序的查询,但我只做了两次,以避免必须在连接组周围添加括号)。RIGHT JOINEMPLOYEELEFTRIGHTLEFT JOINRIGHT JOIN

SELECT
   D.Department_ID,
   D.Department_Name,
   Employees = Count(*) 
FROM
   dbo.DEPARTMENT D
   LEFT JOIN dbo.EMPLOYEE E
      ON D.Department_ID = E.Department_ID
GROUP BY
   D.Department_ID,
   D.Department_Name

另外,我建议您为表使用别名而不是完整的表名。当别名使用一致时,查询变得更容易扫描和理解。拼写整个表名经常会掩盖查询的其他部分。

于 2012-12-18T19:23:24.780 回答