简体   繁体   中英

Alter columns from selected result table in MYSQL

Here the things,I want to join table ' responsibilities ' with fields Name, Direct, Supervise :

Name | Direct | Supervise
 ABC    2        4

and table 'positions' with positionCode, positionID:

positionCode | positionID
   HR/HRM         2
   HR/MN          4

The selected result table will be some thing like this.

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

The ' Direct ' and ' Supervise ' column should be positionCode from 'positions' table. Is there an all-in-one query to output this result? Or I have to query 2 times ?

Try this Query,

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

Output: SEE SQLFiddle DEMO

I think you can join responsibilities twice to the positions table:

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

Follow the link below for a running demo:

SQLFiddle

Try following Query, It should work

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;

check out this SQL Fiddle for proof that this query works:

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

Basically, the query looks as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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