如何使用SQL合并两列?

时间:2018-09-05 09:29:15

标签: mysql sql

给出此表:

id    foo    bar
 1    a      d
 2    b      e
 3    c      f

我想合并foo和bar列,以便获得所有值的结果集:

预期结果:

a
b
c
d
e
f

我的搜索产生了this question,但答案是关于通过以下方式对字段进行修饰:

select CONCAT(foo, bar) as foobar from MyTable

为我产生错误的输出:

ad
be
cf

我不想合并,但我想合并两列。

如何获取foo栏两个字段的所有值的结果?

5 个答案:

答案 0 :(得分:1)

全部使用联盟

      Select foo from a
        Union all
      Select bar from a

答案 1 :(得分:1)

使用UNION ALL:

select foo from tablename
union all
select bar from tablename

答案 2 :(得分:1)

使用UNION

SELECT foo as new_col FROM MyTable
UNION
SELECT bar FROM MyTable

或者UNION ALL,如果您被重复发现。

答案 3 :(得分:1)

SELECT foo FROM t
UNION ALL
SELECT bar FROM t

答案 4 :(得分:1)

关于...

select foo from TABLE UNION ALL select bar from TABLE