分割字符串字段后添加行号

时间:2018-07-13 09:28:13

标签: mysql sql database

我有一个包含2个字段的表: ID:文字 建议:字符串(用逗号分隔的值)

我想进行一次选择查询,该查询将返回一个新的带编号的行,该行代表每个建议及其自己的编号,如原始字符串所示

示例:

enter image description here

注意:每次我运行查询时,必须保证此排名是相同的。

谢谢

3 个答案:

答案 0 :(得分:1)

如果您的数据库版本为 8.0 + ,则可以像下面的select语句中那样使用with recursive cte as子句(在提供了必需的DML之后,例如 create table insert 语句):

mysql> create table tab( ID int, suggestions varchar(25));
mysql> insert into tab values(1,'A,B,C');
mysql> insert into tab values(2,'D,E,F,G,H');
mysql> select q2.*,
              row_number() 
              over 
             (partition by q2.id order by q2.suggestion) as number 
  from 
(       
select distinct
       id, 
       substring_index(
        substring_index(suggestions, ',', q1.nr), 
        ',', 
        -1
       ) as suggestion
    from tab
    cross join
    (with recursive cte as
     (
      select 1 as nr
      union all
      select 1+nr from cte where nr<10
      )
     select * from cte) q1
) q2;

+------+------------+--------+
| id   | suggestion | number |
+------+------------+--------+
|    1 | A          |      1 |
|    1 | B          |      2 |
|    1 | C          |      3 |
|    2 | D          |      1 |
|    2 | E          |      2 |
|    2 | F          |      3 |
|    2 | G          |      4 |
|    2 | H          |      5 |
+------+------------+--------+

答案 1 :(得分:0)

找到here相同的问题已解决。

https://gist.github.com/avoidwork/3749973

答案 2 :(得分:0)

我建议一系列子查询:

select id, substring_index(suggestions, ',', 1) as suggestion, 1
from example
where suggestions is not null
union all
select id, substring_index(substring_index(suggestions, ',', 2), ',', -1) as suggestion, 2
from example
where suggestions like '%,%'
union all
select id, substring_index(substring_index(suggestions, ',', 3), ',', -1) as suggestion, 3
from example
where suggestions like '%,%,%'
union all
select id, substring_index(substring_index(suggestions, ',', 4), ',', -1) as suggestion, 4
from example
where suggestions like '%,%,%,%'
union all
select id, substring_index(substring_index(suggestions, ',', 5), ',', -1) as suggestion, 5
from example
where suggestions like '%,%,%,%,%';

如果每个ID的选项超过5个,则可以轻松扩展此范围。