简体   繁体   English

Mysql查询:将列显示为来自1个表的行

[英]MySql query : Show Columns as Rows from 1 table

Tables : Employee and Project :员工和项目

Employee : 员工人数

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

Project: 项目:

Note: Columns Project_ManagerID and EmployeeID comes from 1 table ( Employee ) 注意: Project_ManagerIDEmployeeID列来自1个表( Employee

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

Project table Explanation: For every Project, there are 2 Employee involve. 项目表说明:每个项目都有2个员工参与。 Project Manager and a Regular Employee 项目经理和正式员工

The query results I'm looking for: 我正在寻找的查询结果:

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

I tried to make a self join but I'm getting difficulties in showing 2 columns in Employee table to display a single Column as Rows like my query result. 我试图进行自我连接,但是在Employee表显示2列以像查询结果一样将单个Columns显示为Rows时遇到了困难。

I always ended up 2 rows.. it should have 2 employee rows for every project. 我总是结束了2行..每个项目应该有2个员工行。

2 Projects * 2 Employees = 4 Rows in total

You can do union all something as 您可以将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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM