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

如何使用MySQL使用一个不同的特定列显示两行?

  •  1
  • zied123456  · 技术社区  · 6 年前

    我有一行在某些条件下应该复制。 例子:

    案例1:

    a  b  c   d   e
    ---------------
    1  4  25  10  NULL
    

    如果e为空,则显示a、b和c:

    1 4 25

    案例2:

    a  b  c   d   e
    ---------------
    1  4  25  10  55
    

    如果e不为Null,则复制该行

    1 4 25 =>a、b、c列

    1 4 10 =>a、b、d列

    4 回复  |  直到 6 年前
        1
  •  3
  •   Andrews B Anthony    6 年前

    使用此查询

    使用union可以实现这个用例

    select a,b,c from table
    union all
    select a,b,d from table where e is not null
    
        2
  •  1
  •   Gordon Linoff    6 年前

    如果不想扫描表两次,那么可以使用 cross join 还有一些逻辑:

    select a, b, 
           (case when n = 1 then c else d end)
    from t cross join
         (select 1 as n union all select 2) n
    where n = 1 or
          (n = 2 and e is not null);