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

MySQL创建视图:重复的行,在4列中有不同的值,并且不是空的,mysql,sql,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 Yea

我有一张像这样的桌子:

   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的新手,我认为复制/添加/编辑是不可能的,因为我非常感谢您的建议

执行UNION ALL,为每个Un列选择一个:

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

order by CPID, CID, Ux
在创建视图时,MySQL似乎不喜欢上面查询的派生表。再来一次尝试:

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
一种方法使用union all:

诀窍在于条件if有多个单元。这需要计算每行中非空值的数量。此方法使用MySQL的一个特性,其中布尔表达式被视为1表示true,0表示false。因此,将布尔表达式相加会产生计数的效果。

您可以使用UNION ALL:


我不理解where子句,为什么需要检查未选择的空列?我有一种感觉,我们中的一个人误解了这个问题,尝试使用Union All/PIVONTBY将使答案完整。@1000111,按要求!这是正确的,但我得到了这个错误:1349-View的SELECT在FROM中包含一个子查询clause@Hemin-为子查询指定别名。。。在ux不在的地方作为枢轴NULL@MatBailie,这是某种MySQL限制吗?
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
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;
SELECT CPID,CID,U1 FROM YourTable
WHERE U1 IS NOT NULL
UNION ALL
SELECT CPID,CID,U2 FROM YourTable
WHERE U2 IS NOT NULL
UNION ALL
SELECT CPID,CID,U3 FROM YourTable
WHERE U3 IS NOT NULL
UNION ALL
SELECT CPID,CID,U4 FROM YourTable
WHERE U4 IS NOT NULL