简体   繁体   中英

How to make an sql query that combines values across multiple columns into a single one in MySQL?

Assuming I have the following:

swim_names, football_names, soccer_names, swim_age
John, Johnny, Johnson, 5
Mike, Michael, Mike, 2
Jo, Joe, Joey, 7

How can I construct an SQL query such that I can get the following output below:

names, age
John, 5
Johnny, null
Johnson, null
Mike, 2
Michael, null
Mike, null
Jo, 7
Joe, null
Joey, null

Note that:

  1. names are distict names across all three of the "_names" columns
  2. swim_age is available only for the names in "swim_names"

Try to use UNION ALL like:

 SELECT swim_names as Names, swim_age as age FROM tbl
 UNION ALL
 SELECT football_names as Names, null as age FROM tbl
 UNION ALL
 SELECT soccer_names as Names, null as age FROM tbl

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