简体   繁体   中英

SELECT same data from EITHER one of two tables

I have to do a bit of time-keeping. Some employees are part of the first team and some are part of the second team. I need to display a simple table of who signed in and when along with some other basic information.

If both tables team1 and team2 have the same columns ( first_name , last_name and date ) though it's absolutely guaranteed that only one of those tables will return data per row how do I avoid using a bunch of aliases ( first_name AS team1_first_name ) and just always have SQL return first_name ?

An example query:

SELECT *
FROM associates AS ac
LEFT JOIN team1 AS t1 ON (t1.id = ac.team1) 
LEFT JOIN team2 AS t2 ON (t2.id = ac.team2) 
ORDER BY ac.date DESC LIMIT 100;

Since one of t1.first_name and t2.first_name is null and the other is not,
you can use coalesce() in the select statement like this:

select
  coalesce(t1.first_name, t2.first_name) first_name,
  coalesce(t1.last_name, t2.last_name) last_name,
  .............................................

If you don't want to type in all the columns and employees are on only one team, you can union the tables before the join :

SELECT a.*, t.*
FROM associates a JOIN
     ((SELECT t1.* FROM team1 t1) UNION ALL
      (SELECT t2.* FROM team2 t2)
     ) t
     ON t.id IN (ac.team1, ac.team2)
ORDER BY a.date DESC
LIMIT 100;

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