简体   繁体   中英

Create temp column in SELECT statement with data from same table

I have a table that contains folder information, I would like to add one column in my select query without changing the table itself.

case_id | folder_id | parent_folder_id | folder_name
123       C488785     null               case 1
123       F488785     C488785            folder 1
123       SF488785    F488785            subfolder 1

I want to add a fifth column containing the name of the parent_folder "parent_folder_name".

Result as below:

case_id | folder_id | parent_folder_id | folder_name | parent_folder_name
123       C488785     null               case 1        null
123       F488785     C488785            folder 1      case 1
123       SF488785    F488785            subfolder 1   folder 1

Just use a self join:

select t.*, tp.folder_name as parent_folder_name
from t left join
     t tp
     on tp.case_id = t.case_id and
        tp.folder_id = t.parent_folder_id;

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