简体   繁体   中英

Query for replacing one field with the value of corresponding field

I have a table called emp :

╔════╦══════╦═══════════╗
║ id ║ name ║ fathersid ║
╠════╬══════╬═══════════╣
║  1 ║  a   ║    2      ║
║  2 ║  s   ║   null    ║
║  3 ║  d   ║    1      ║
║  4 ║  f   ║    3      ║
╚════╩══════╩═══════════╝

I want to print the name corresponding with its father's name.

I have written the following query:

SELECT name,
    (SELECT name FROM emp WHERE father_id = id)
FROM emp

Is this correct?

If not, then what is the right answer?

I prefer to solve this type of problem using a self-join:

SELECT e1.name AS name, COALESCE(e2.name, 'Not Available') AS fatherName
FROM emp e1 LEFT JOIN emp e2
    ON e1.fathersid = e2.id

Its almost correct, you need to alias the tables so the reader will know you are comparing the inner query to the outer query :

SELECT t.NAME,
       (SELECT s.name FROM emp s where s.id = t.father_id) as Father_name
FROM emp t

You can do this with a join:

SELECT t.name,s.name as Father_Name
FROM emp t
LEFT OUTER JOIN emp s
 ON(t.father_id = s.id)

In Oracle you can use a hierachical query (which only requires a single table scan - compared to using joins or correlated sub-queries which require multiple table scans):

SELECT name,
       PRIOR name AS fathers_name
FROM   emp
START WITH       fathersid = NULL
CONNECT BY PRIOR empno = fathersid;

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