如何从一列中分离多个数据?

时间:2013-04-04 18:27:44

标签: mysql database string

我遇到了问题 - 我需要从列Column3(分隔符“|”)中分离数据。

Column1 Column2 Column3
7        23      567|568|85|532|296|581|300|265|577|330|563|423|55|442
8         0      242
9         0      242
10       23      567|568|85|532|296|581|300|265|577|330|563|423|55|442
14        4      330|563|423|134|242

Column1是ID,Column2是'|'对于每一行计数,第3列是应该在新行中分开的数据。

我的输出应该如下:

Column1 Column4
7       567
8       242
9       242
10      567
14      330
7       568
10      568
14      563

我写了如下所示的联盟,但我不想迭代它60次......

select 
    Column1,
    substring_index(substring_index(Column2,'|',1),'|',-1) as Column2
from Table1
union
select
    Column1,
    substring_index(substring_index(Column2,'|',2),'|',-1) as Column2
from Table1

你能帮我找到更好的解决方案吗?

BR

1 个答案:

答案 0 :(得分:2)

您可以使用数字列表执行此操作。这是一个例子:

select Column1,
       substring_index(substring_index(Column2,'|', nums.n),'|',-1) as Column2
from Table1 t1 cross join
      (select (n1.n - 1) * 12 + (n2.n - 1)*3 + n3.n as n
       from  (select 1 as n union all select 2 union all select 3 union all select 4 union all select 5
             ) n1 cross join
             (select 1 as n union all select 2 union all select 3 union all select 4 
             ) n2 cross join
             (select 1 as n union all select 2 union all select 3 
             ) n3
      ) nums