MySQL创建视图:重复的行在4列中具有不同的值而不是空的

时间:2016-08-23 11:46:33

标签: mysql sql

我有一张表:

   CPID  CID    U1     U2     U3     U4
    1    44    Day    Hour   Null   Year
    2    45    Day    Year   Null   Null

如果有多种单位(Ux)

,我想创建一个复制行的视图

以上将是这样的:

   CPID  CID    Ux     
    1    44    Day
    1    44    Hour
    1    44    Year
    2    45    Day
    2    45    Year

到目前为止我所做的只是:

SELECT CPID AS CPID,
  CID AS CID,
  Concat_Ws(',', T1, T2, T3, T4) AS Ux
上面的

只会显示:

   CPID  CID    Ux     
    1    44    Day,Hour,Year
    2    45    Day,Year

我仍然是MySQL的新手,我认为制作复制/添加/编辑是不可能的,我会感谢您的建议。

3 个答案:

答案 0 :(得分:2)

为每个U n 列做一个UNION ALL,一个SELECT:

select CPID, CID, UX
from
(
select CPID, CID, U1 as UX from tablename
union all
select CPID, CID, U2 as UX from tablename
union all
select CPID, CID, U3 as UX from tablename
union all
select CPID, CID, U4 as UX from tablename
) dt
where ux is not null

并且,如果结果集顺序很重要,请在结尾处添加以下行:

order by CPID, CID, Ux

似乎MySQL在CREATE VIEW时不喜欢上述查询的派生表。这是另一个尝试:

create view viewname (CPID, CID, UX) AS
select CPID, CID, U1 from tablename
where U1 is not null
union all
select CPID, CID, U2 from tablename
where U2 is not null
union all
select CPID, CID, U3 from tablename
where U3 is not null
union all
select CPID, CID, U4 from tablename
where U4 is not null

答案 1 :(得分:0)

一种方法使用union all

select cpid, cid, u1 as unit
from t
where u1 is not null and
      (u1 is not null) + (u2 is not null) + (u3 is not null) + (u4 is not null) >= 2
union all
select cpid, cid, u2 as unit
from t
where u2 is not null and
      (u1 is not null) + (u2 is not null) + (u3 is not null) + (u4 is not null) >= 2
select cpid, cid, u3 as unit
from t
where u3 is not null and
      (u1 is not null) + (u2 is not null) + (u3 is not null) + (u4 is not null) >= 2
select cpid, cid, u4 as unit
from t
where u4 is not null and
      (u1 is not null) + (u2 is not null) + (u3 is not null) + (u4 is not null) >= 2;

诀窍是条件“如果有多种单位”。这需要计算每行中的非NULL值的数量。此方法使用MySQL的一个功能,其中布尔表达式被视为“1”表示true,“0”表示false。因此,将布尔表达式一起添加可以计算它们。

答案 2 :(得分:0)

您可以使用ABS()

UNION ALL