不知道该如何表达文章标题,但我有一个数据表,如:
ID1 F1 F2 F3
X1 Enabled Disabled Disabled
X2 Disabled Enabled Enabled
我想把它做成:
ID1 Fields
X1 F1
X2 F2
X2 F3
最初我有一种类似的形式
SELECT ID1, CONCAT_WS(',', IF(F1='Enabled','F1',NULL), IF(F2='Enabled','F2',NULL), ...)
但我发现mysql并没有内置string_split((函数来将连接的内容分解为一个数组,并向下复制ID1字段。
我试过在这里使用CASE WHEN
,但它似乎不合适,因为我不想基于匹配覆盖值,我只想要所有字段。我觉得我错过了摆在我面前的一个相对简单的手术。有什么建议吗?
MySql不支持unpvot
语法,也不支持values
构造,这只剩下union
:
select id1, fields from (
select id1, case when f1='enabled' then 'f1' end as Fields from t
union all
select id1, case when f2='enabled' then 'f2' end from t
union all
select id1, case when f3='enabled' then 'f3' end from t
)u
where fields is not null