简体   繁体   中英

MYSQL: How to make it virtual column in select Query?

Below is the my question any one have idea how to resolve this issue:

Example Query:

SELECT id, table2.id as global_id, table3.id as global_id 
FROM table1 
LEFT JOIN table2 
  ON ( table1.id = table2.tab1_id ) 
LEFT JOIN table3 
  ON ( table1.id = table3.tab1_id ) 
WHERE etc etc

Basically i don't want to write two times "global_id" column in the select statement and also in the some rows have id = NULL

Can you please write working query here. How can i get id value of all rows in the global_id column ?

Thanks

Use COALESCE :

SELECT table1.id, COALESCE(table2.id, table3.id) as global_id 
FROM table1 
LEFT JOIN table2 
  ON ( table1.id = table2.tab1_id ) 
LEFT JOIN table3 
  ON ( table1.id = table3.tab1_id ) 
WHERE etc etc

Guess you need this:

SELECT id, table2.id as global_id
FROM table1 
LEFT JOIN table2 
  ON ( table1.id = table2.tab1_id ) 
WHERE etc etc
UNION ALL
SELECT id, table3.id as global_id 
FROM table1 
LEFT JOIN table3 
  ON ( table1.id = table3.tab1_id ) 
WHERE etc etc

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