首页 > 解决方案 > 使用分隔符“,”递归地将列拆分为 SQLite 上的不同行

问题描述

我有一个这样的 SQLite 表:

表名:苏拉特

表名是“苏拉特”

但我想使用 SQLite 查询将 id_ayat 拆分为不同的行,预期结果如下:

  _id|id_surat|id_ayat
  ---+--------+-------
  3  |   2    |  112
  3  |   2    |  213
  3  |   3    |  19
  3  |   3    |  83
  3  |   3    |  85
  3  |   3    |  102

那可能吗?我可以在 SQLite 格式中使用什么查询?

标签: sqliterecursiondelimitersubstr

解决方案


使用递归CTE

with recursive cte as (
  select _id, id_surat, id_ayat, 
    id_ayat + 0 col 
  from tablename 
  union all 
  select _id, id_surat, trim(substr(id_ayat, length(col) + 2)), 
    trim(substr(id_ayat, length(col) + 2)) + 0 
  from cte  
  where instr(id_ayat, ',')
)
select _id, id_surat, col id_ayat 
from cte
order by _id, id_surat

请参阅演示
结果:

| _id | id_surat | id_ayat |
| --- | -------- | ------- |
| 3   | 2        | 112     |
| 3   | 2        | 213     |
| 3   | 3        | 19      |
| 3   | 3        | 83      |
| 3   | 3        | 85      |
| 3   | 3        | 102     |

推荐阅读