如何在MySQL中将多个列的值组合成一个SQL查询?

时间:2014-03-16 23:49:00

标签: mysql

假设我有以下内容:

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

如何构建SQL查询,以便我可以在下面获得以下输出:

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

请注意:

  1. 名称是所有三个" _names"的名称。列
  2. swim_age仅适用于" swim_names"
  3. 中的名称

1 个答案:

答案 0 :(得分:0)

尝试使用UNION ALL之类的:

 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