用Count连接3个表

时间:2018-06-30 06:14:24

标签: mysql sql join count

我正在尝试编写一个简单的查询,该查询将显示所有项目及其团队成员总数,并按项目按字母顺序排序。如果项目没有分配团队成员,则该项目仍应包含在输出中。

CREATE TABLE Project ( ID INT IDENTITY(1,1), ProjectName VARCHAR(50), DueDate 
DATE)
CREATE TABLE Employee ( ID INT IDENTITY(1,1), EmployeeName VARCHAR(50) )
CREATE TABLE ProjectAssignment ( ID INT IDENTITY(1,1), ProjectID INT, 
EmployeeID INT)

INSERT INTO Project VALUES ('Alpha', '1/1/2040'), ('Bravo', '3/1/2030'), 
('Charlie', '2/1/2017'), ('Delta', '4/1/2017')
INSERT INTO Employee VALUES ('John'), ('Beth'), ('Tom'), ('Kim'), ('Jack')
INSERT INTO ProjectAssignment VALUES   (1, 1), (1, 2), (2, 2), (2, 3), (3, 
3), (3, 4), (1, 3)

--TABLE Project:
ID  ProjectName DueDate
1   Alpha   2040-01-01
2   Bravo   2030-03-01
3   Charlie 2017-02-01
4   Delta   2017-04-01

--TABLE Employee:
ID  EmployeeName 
1   John
2   Beth
3   Tom
4   Kim
5   Jack

--TABLE ProjectAssignment:
ID  ProjectID   EmployeeID
1   1   1
2   1   2
3   2   2
4   2   3
5   3   3
6   3   4
7   1   3

这是我的错误查询:

SELECT n.ProjectName, Count(t.ProjectID) as NumMembers
FROM Project p 
LEFT JOIN ProjectAssignment t ON p.EmployeeID = t.EmployeeID
LEFT JOIN employee e ON e.ProjectID = t.ProjectID
GROUP BY n.Project
ORDER BY n.Project

所需结果:

| ProjectName | NumMembers  |
+-------------+-------------+
| Alpha       | 3           |
| Bravo       | 2           |
| Charlie     | 2           |
| Delta       | null        |

4 个答案:

答案 0 :(得分:2)

请尝试此Mysql查询。这样可以解决您的问题。我们不需要员工表联接。如果您不从employee表中获取任何数据,则不要在join中添加employee表。

  SELECT 
    p.name AS ProjectName,
    Count( t.employeeID ) AS NumMembers 
  FROM 
    Project p 
    LEFT JOIN ProjectAssignment t ON p.id = t.projectID
  GROUP BY 
    p.name

输出:

Project name        NumMembers
Alpha                   3
Bravo                   2
Charlie                 2
Delta                   0

答案 1 :(得分:1)

几件事

左联接ProjectAssignment t ON p.EmployeeID = t.EmployeeID 错误,因为您可以看到p.EmployeeID在表Project上不存在

根本不需要加入employee

最后我也不知道您的字段名称如何。您在示例数据中发布名称,并且在查询和ddl中使用projectName(已更改为DDL而不是查询)

SELECT p.ProjectName, Count(DISTINCT pa.EmployeeID) as NumMembers
FROM Project p 
LEFT JOIN ProjectAssignment pa ON p.ID   = pa.ProjectID   
GROUP BY p.ID, p.ProjectName 
ORDER BY p.ProjectName 

http://sqlfiddle.com/#!18/36df5/1

答案 2 :(得分:0)

只需使用它(似乎加入条件混合):

SELECT p.ProjectName, Count(t.ProjectID) as NumMembers
FROM Project p 
LEFT JOIN ProjectAssignment t ON p.ID = t.ProjectID
LEFT JOIN employee e ON t.EmployeeID = e.ID
GROUP BY p.ProjectName
ORDER BY p.ProjectName;

ProjectName NumMembers
   Alpha    3
   Bravo    2
   Charlie  2
   Delta    0

SQL Fiddle Demo

答案 3 :(得分:0)

SELECT n.ProjectName, Count(t.ProjectID) as NumMembers FROM Project n LEFT JOIN ProjectAssignment t ON n.id = t.ProjectID GROUP BY t.ProjectID ORDER BY n.ProjectName

运行此查询