我有一个具有以下结构的表
员工关系表:
| FromEmployeeRelation | ToEmployeeRelation | CreatedAt | UpdatedAt |
+----------------------+--------------------+-----------+-----------+
| 2 | 3 | Date | Date |
关系表
| Id | EmployeeId | CreatedAt | UpdatedAt |
+----+------------+-----------+-----------+
|2 | 5 | Date | Date |
|3 | 7 | Date | Date |
来自员工关系表中FromEmployeeRelation和ToEmployeeRelation的外键中的Relation表中的Id
我正在尝试从员工关系表中获取结果中的实际员工ID信息
结果
| FromEmployeeId | ToEmployeeId | FromEmployeeRelation | ToEmployeeRelation
+----------------+--------------+----------------------+-------------------
| 5 | 7 | 2 | 3
从加入我可以从一个关系获得EmployeeId,但我不知道如何获得两个关系的员工ID。
如何做到这一点? 感谢
答案 0 :(得分:2)
试试这个:
select e1.EmployeeId as FromEmployeeId ,
e2.EmployeeId as ToEmployeeId ,
er.FromEmployeeRelation,
er.ToEmployeeRelation
from emp_relation er
inner join emp e1 on er.FromEmployeeRelation=e1.id
inner join emp e2 on er.ToEmployeeRelation=e2.id
答案 1 :(得分:2)
选项1:在两个不同的列SQL Fiddle
上加入单个表SELECT
from_tbl.EmployeeId AS FromEmployeeId,
to_tbl.EmployeeId AS ToEmployeeId,
e.FromEmployeeRelation,
e.ToEmployeeRelation
FROM EmployeeRelation e
INNER JOIN Relation from_tbl ON e.FromEmployeeRelation = from_tbl.Id
INNER JOIN Relation to_tbl ON e.ToEmployeeRelation = to_tbl.Id
选项2:使用子查询SQL Fiddle
SELECT
(SELECT from_tbl.EmployeeId FROM Relation from_tbl WHERE e.FromEmployeeRelation = from_tbl.Id) AS FromEmployeeId,
(SELECT to_tbl.EmployeeId FROM Relation to_tbl WHERE e.ToEmployeeRelation = to_tbl.Id) AS ToEmployeeId,
e.FromEmployeeRelation,
e.ToEmployeeRelation
FROM EmployeeRelation e