代码之家  ›  专栏  ›  技术社区  ›  k0pernikus

如何使用sql合并两列?[副本]

  •  1
  • k0pernikus  · 技术社区  · 7 年前

    鉴于此表:

    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 回复  |  直到 7 年前
        1
  •  1
  •   Fahmi    7 年前

    使用UNION ALL:

    select foo from tablename
    union all
    select bar from tablename
    
        2
  •  1
  •   sagi    7 年前

    使用 UNION

    SELECT foo as new_col FROM MyTable
    UNION
    SELECT bar FROM MyTable
    

    UNION ALL 如果你对复制品感兴趣。

        3
  •  1
  •   mvp    7 年前
    SELECT foo FROM t
    UNION ALL
    SELECT bar FROM t
    
        4
  •  1
  •   Zaynul Abadin Tuhin    7 年前

    使用Union all

          Select foo from a
            Union all
          Select bar from a
    
        5
  •  1
  •   Jens    7 年前

    那么...怎么样

    select foo from TABLE UNION ALL select bar from TABLE