简体   繁体   English

MySQL将多列拆分成多行

[英]MySQL split up multiple columns into multiple rows

I have a customer supplied dataset which looks like this: (simplified) 我有一个客户提供的数据集,如下所示:(简化)

|ForiegnKey|Code1|Code2|Code3|  
|==========|=====|=====|=====|  
|A         |10   |20   |30   |  
|A         |10   |20   |30   |  
|B         |100  |200  |     |  
|C         |25   |35   |40   |  
|D         |1000 |     |     | 
|E         |     |     |9999 |

For the final product, I need this entered in a new table 1 code at a time, so like so: 对于最终产品,我需要一次在新表中输入1个代码,如下所示:

|ForiegnKey|Sequence|Code|
|A         |1       |10  |
|A         |2       |20  |
|A         |3       |30  |
|B         |1       |100 |
|C         |1       |25  |
|C         |2       |35  |
|C         |3       |40  |
|D         |1       |1000|
|E         |1       |9999|

For my question, is there a simple way to do this one in query that doesn't involve using unions? 对于我的问题,是否有一种简单的方法可以在不涉及使用联合的查询中执行此操作?
I have to generate the sequence number based on the Value of the ForiegnKey (ie in the Case of ForiegnKey E, even tho it was in Column Code3, I need it to have a Sequence of 1.) My current thought path is that if I can get this out of the table without using a Union, I could generate the Sequence ID in the same statement. 我必须根据ForiegnKey的值生成序列号(即在ForiegnKey E的情况下,即使它在列Code3中,我需要它的序列为1.)我当前的思路是如果我可以在不使用Union的情况下将其从表中取出,我可以在同一语句中生成序列ID。
Empty code values such as D-2 and 3, and E-1 and 2 should be skipped. 应跳过空代码值,例如D-2和3以及E-1和2。
I have started working on this using a temporary table but thought I would check here and see if there was an easier way. 我已经开始使用临时表来处理这个问题,但我想我会在这里查看是否有更简单的方法。

Thanks 谢谢

You sound more interested in getting the results in one batch than in avoiding UNIONS. 你听起来更有兴趣在一个批次中获得结果,而不是避免使用UNIONS。 Here you go: 干得好:

set @last_key = null;
set @seq = 1;
select foreignkey, case when @last_key is null or @last_key != foreignkey then @seq := 1 else @seq := @seq + 1 end as sequence, code, @last_key := foreignkey as foo  from (
  select foreignkey, code1 as code
  from dataset
  where code1 is not null
  union
  select foreignkey, code2
  from dataset
  where code2 is not null
  union
  select foreignkey, code3
  from dataset
  where code3 is not null
  order by 1
) foo;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM