更改MYSQL中选定结果表中的列

时间:2016-07-18 04:46:37

标签: mysql

在这里,我想加入表格responsibilities'使用字段Name, Direct, Supervise

Name | Direct | Supervise
 ABC    2        4

和表'职位'使用positionCode,positionID:

positionCode | positionID
   HR/HRM         2
   HR/MN          4

选择的结果表将是这样的。

Name | Direct | Supervise
 ABC   HR/HRM    HR/MN

' Direct'和' Supervise'列应该是positionCode来自'位置'表。是否有一体化查询输出此结果?或者我要查询2次?

4 个答案:

答案 0 :(得分:3)

尝试此查询,

SELECT r.Name,
       p1.positionCode AS Direct,
       p2.positionCode AS Supervise
FROM responsibilities r
LEFT JOIN positions p1
    ON r.Direct = p1.positionID
LEFT JOIN positions p2
    ON r.Supervise = p2.positionID

输出:SEE SQLFiddle DEMO

答案 1 :(得分:2)

我认为您可以responsibilities两次加入positions表:

SELECT r.Name,
       COALESCE(p1.positionCode, 'Direct is N/A') AS Direct,
       COALESCE(p2.positionCode, 'Supervise is N/A') AS Supervise
FROM responsibilities r
LEFT JOIN positions p1
    ON r.Direct = p1.positionID
LEFT JOIN positions p2
    ON r.Supervise = p2.positionID

请按照以下链接查看正在运行的演示:

SQLFiddle

答案 2 :(得分:0)

尝试以下查询,它应该可以正常工作

select R.Name,(select P.positionCode where R.Direct=P.positionID) as 
Direct,(select P.positionCode where R.Supervise=P.positionID) as 
Supervise from Responsibilites R, Positions P;

答案 3 :(得分:0)

查看此SQL小提琴,了解此查询是否有效:

http://sqlfiddle.com/#!9/13845c/4/0

基本上,查询如下所示:

SELECT r.Name, p1.positionCode As Direct, p2.positionCode as Supervise
FROM responsibilities r 
LEFT JOIN positions p1 ON r.Direct = p1.positionID
LEFT JOIN positions p2 ON r.Supervise = p2.positionID