我有以下架构:
*Project*
ID(PK) NAME
1 Alpha
2 Bravo
3 Charlie
4 Delta
*Employee*
ID(PK) NAME
1 Kevin
2 Mike
3 Eric
4 Ira
5 Peter
*Project Assignment*
ID(PK) ProjectID(FK) EmployeeID(FK)
1 1 1
2 1 2
3 2 2
4 2 3
5 3 3
6 3 4
7 1 3
我想写一些查询:
1)显示所有已分配的项目及其团队成员。
期望的输出:
Project TeamMembers
Alpha Eric
Alpha Kevin
Alpha Mike
Bravo Eric
Bravo Mike
Charlie Eric
Charlie Ira
2)仅显示Alpha项目及其团队成员,并显示按降序排序的团队成员的名称。
期望的输出:
ID TeamMember
Alpha Mike
Alpha Kevin
Alpha Eric
最简单的查询是什么样的?
其他问题:
每个项目的团队成员数量总和是什么?
期望的结果:
+-------------+-------------+
| ProjectName | NumMembers |
+-------------+-------------+
| Alpha | 3 |
| Bravo | 2 |
| Charlie | 2 |
+-------------+-------------+
答案 0 :(得分:0)
create table Project (ID int, NAME varchar(50));
insert into Project values
(1, 'Alpha'),
(2, 'Bravo'),
(3, 'Charlie'),
(4, 'Delta');
create table Employee (ID int, NAME varchar(50));
insert into Employee values
(1, 'Kevin'),
(2, 'Mike'),
(3, 'Eric'),
(4, 'Ira'),
(5, 'Peter');
create table Project_Assignment (ID int, ProjectID int, EmployeeID int);
insert into Project_Assignment values
(1, 1, 1),
(2, 1, 2),
(3, 2, 2),
(4, 2, 3),
(5, 3, 3),
(6, 3, 4),
(7, 1, 3);
解决方案#1:
您需要将Project_Assignment
表加入Project
和Employee
表,分别获取两列:
select p.name as projectname,
e.name as TeamMembers
from project_assignment pa
join project p on pa.projectid = p.id
join employee e on pa.employeeid = e.id
order by projectname, TeamMembers desc;
<强>结果:强>
+-------------+-------------+
| projectname | TeamMembers |
+-------------+-------------+
| Alpha | Mike |
| Alpha | Kevin |
| Alpha | Eric |
| Bravo | Mike |
| Bravo | Eric |
| Charlie | Ira |
| Charlie | Eric |
+-------------+-------------+
解决方案#2:
在上述查询中添加where
子句,仅过滤Alpha
项目:
select p.name as projectname,
e.name as TeamMembers
from project_assignment pa
join project p on pa.projectid = p.id
join employee e on pa.employeeid = e.id
where p.name = 'Alpha'
order by projectname, TeamMembers desc;
<强>结果:强>
+-------------+-------------+
| projectname | TeamMembers |
+-------------+-------------+
| Alpha | Mike |
| Alpha | Kevin |
| Alpha | Eric |
+-------------+-------------+