数据库:MYSQL WORKBENCH
请找到我下面的问题,请您帮我一下,
现有表,列为( 1001, 1, 1, 0, 1;1002, 1, 0, 0,1)
,行为
eid ||cola ||colb|| colc ||cold
新表应该看起来像(手动创建):表1(带有ID和描述)
id||description == Rows as (1, abc; 2, bcd; 3, cde; 4, def)
其中abc,bcd,cde,def ==是cola,colb,colc,冷描述
表2 ==有两列
eid ||Group id
从现有表迁移后,表2如下所示
Rows as (1001,1; 1001,2;1001,4;1002,1;1002,4)
请建议我如何编写查询。
最佳答案
尝试这样:
insert into table2
select col.id,table1.id FROM col
INNER JOIN table1 on case when col.cola=1 then 1 end =table1.id
UNION ALL
select col.id,table1.id FROM col
INNER JOIN table1 on case when col.colb=1 then 2 end =table1.id
UNION ALL
select col.id,table1.id FROM col
INNER JOIN table1 on case when col.colc=1 then 3 end =table1.id
UNION ALL
select col.id,table1.id FROM col
INNER JOIN table1 on case when col.cold=1 then 4 end =table1.id