MySql查询:从1个表中将列显示为行

时间:2014-12-07 16:09:13

标签: mysql database join self-join

表格:员工和项目

员工

EmployeeID|  Username | 
----------+-----------+
1         | Manager1  | 
2         | Manager2  | 
3         | Employee3 | 
4         | Employee4 | 
5         | Employee5 | 

项目:

注意: Project_ManagerID EmployeeID 来自1个表(员工

 ProjectID | Project_Name| Project_ManagerID | EmployeeID
-----------+-------------+-------------------+---------
1          | Project 1   | 1                 | 3
2          | Project 2   | 1                 | 4

项目表说明: 对于每个项目,有2名员工参与。项目经理和普通员工

查询结果我正在寻找:

ProjectID  | EmployeeID | Username  |
-----------+------------+-----------+
1          | 1          | Manager1  |
1          | 3          | Employee3 |
2          | 1          | Manager1  |
2          | 4          | Employee4 |

我尝试进行自我加入,但是我在在Employee表中显示2列以显示单个列作为行(例如我的查询结果)时遇到了困难。

我总是最多2行..每个项目应该有2个员工行。

2 Projects * 2 Employees = 4 Rows in total

1 个答案:

答案 0 :(得分:2)

你可以union all做某事

select
p.ProjectID,e.EmployeeID,e.Username 
from Project p 
join Employee e on e.EmployeeID = p.Project_ManagerID

union all

select
p.ProjectID,e.EmployeeID,e.Username 
from Project p 
join Employee e on e.EmployeeID = p.EmployeeID