我正在研究MySQL数据库。
我有一个表empreporting
,此表包含
employeeid
和reportingemployeeid
列
SELECT e3.`ReportingEmployeeId` AS Level0,e2.`ReportingEmployeeId` AS Level1,e1.`ReportingEmployeeId` AS Level2,e1.`EmployeeId` AS Level3
FROM empreporting e1
LEFT JOIN empreporting e2 ON e1.`ReportingEmployeeId` = e2.`EmployeeId`
LEFT JOIN empreporting e3 ON e2.`ReportingEmployeeId` = e3.`EmployeeId`
以上查询给出以下结果:
Level0 Level1 Level2 Level3 \N \N 379 369 \N 379 484 372 \N \N \N 379
所需的结果格式为:
Level0 Level1 Level2 Level3 379 369 \N \N 379 484 372 \N 379 \N \N \N
请任何人帮助我。 提前致谢
普拉卡什
答案 0 :(得分:2)
最后写的查询
SELECT
CASE
WHEN e3.`ReportingEmployeeId` IS NOT NULL THEN e3.`ReportingEmployeeId`+1000000
WHEN e3.`ReportingEmployeeId` IS NULL AND e2.`ReportingEmployeeId` IS NOT NULL THEN e2.`ReportingEmployeeId`
WHEN e3.`ReportingEmployeeId` IS NULL AND e2.`ReportingEmployeeId` IS NULL AND e1.`ReportingEmployeeId` IS NOT NULL THEN e1.`ReportingEmployeeId`
WHEN e3.`ReportingEmployeeId` IS NULL AND e2.`ReportingEmployeeId` IS NULL AND e1.`ReportingEmployeeId` IS NULL AND e1.`EmployeeId` IS NOT NULL THEN e1.`EmployeeId`
END AS Level0,
CASE
WHEN e3.`ReportingEmployeeId` IS NOT NULL THEN e2.`ReportingEmployeeId`
WHEN e3.`ReportingEmployeeId` IS NULL AND e2.`ReportingEmployeeId` IS NOT NULL THEN e1.`ReportingEmployeeId`
WHEN e3.`ReportingEmployeeId` IS NULL AND e2.`ReportingEmployeeId` IS NULL AND e1.`ReportingEmployeeId` IS NOT NULL THEN e1.`EmployeeId`
WHEN e3.`ReportingEmployeeId` IS NULL AND e2.`ReportingEmployeeId` IS NULL AND e1.`ReportingEmployeeId` IS NULL AND e1.`EmployeeId` IS NOT NULL THEN NULL
END AS Level1,
CASE
WHEN e3.`ReportingEmployeeId` IS NOT NULL THEN e1.`ReportingEmployeeId`
WHEN e3.`ReportingEmployeeId` IS NULL AND e2.`ReportingEmployeeId` IS NOT NULL THEN e1.`EmployeeId`
WHEN e3.`ReportingEmployeeId` IS NULL AND e2.`ReportingEmployeeId` IS NULL AND e1.`ReportingEmployeeId` IS NOT NULL THEN NULL
WHEN e3.`ReportingEmployeeId` IS NULL AND e2.`ReportingEmployeeId` IS NULL AND e1.`ReportingEmployeeId` IS NULL AND e1.`EmployeeId` IS NOT NULL THEN NULL
END AS Level2,
CASE
WHEN e3.`ReportingEmployeeId` IS NOT NULL THEN e1.`EmployeeId`
WHEN e3.`ReportingEmployeeId` IS NULL AND e2.`ReportingEmployeeId` IS NOT NULL THEN NULL
WHEN e3.`ReportingEmployeeId` IS NULL AND e2.`ReportingEmployeeId` IS NULL AND e1.`ReportingEmployeeId` IS NOT NULL THEN NULL
WHEN e3.`ReportingEmployeeId` IS NULL AND e2.`ReportingEmployeeId` IS NULL AND e1.`ReportingEmployeeId` IS NULL AND e1.`EmployeeId` IS NOT NULL THEN NULL
END AS Level3
FROM empreporting e1
LEFT JOIN empreporting e2 ON e1.`ReportingEmployeeId` = e2.`EmployeeId`
LEFT JOIN empreporting e3 ON e2.`ReportingEmployeeId` = e3.`EmployeeId`
答案 1 :(得分:0)
试
SELECT e1.EmployeeId AS Level0,e2.`EmployeeId` AS Level1,e3.`EmployeeId` AS Level2,e3.`ReportingEmployeeId` AS Level3
FROM empreporting e1
LEFT JOIN empreporting e2 ON e1.`ReportingEmployeeId` = e2.`EmployeeId`
LEFT JOIN empreporting e3 ON e2.`ReportingEmployeeId` = e3.`EmployeeId`