且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用sqlite在零件中拆分值

更新时间:2023-11-27 08:32:52

是的,解决方案是使用递归公用表表达式:

 ,其中x(one,firstone,rest)为
(选择一个,substr(many,1,instr(many,',')-1)作为firstone,substr(many,instr(many, ',')+ 1)作为其他数据的休止符,例如%,%
UNION ALL
选择一个,substr(rest,1,instr(rest,',')-1)作为firstone,substr(rest,instr(rest,',')+ 1)从x处作为休息处,如%,% LIMIT 200

从x UNION ALL中选择一个,firstone ,从x处休息,而不是像%,%
那样按1休息;

输出:

  a | a1 
a | a2
a | a3
b | b1
b | b3
c | c2
c | c1


I'm struggling to convert

a | a1,a2,a3
b | b1,b3
c | c2,c1

to:

a | a1
a | a2
a | a3
b | b1
b | b2
c | c2
c | c1

Here are data in sql format:

CREATE TABLE data(
  "one"  TEXT,
  "many" TEXT
);
INSERT INTO "data" VALUES('a','a1,a2,a3');
INSERT INTO "data" VALUES('b','b1,b3');
INSERT INTO "data" VALUES('c','c2,c1');

The solution is probably recursive Common Table Expression.




Here's an example which does something similar to a single row:

WITH RECURSIVE list( element, remainder ) AS (
    SELECT NULL AS element, '1,2,3,4,5' AS remainder
        UNION ALL
    SELECT
        CASE
            WHEN INSTR( remainder, ',' )>0 THEN
                SUBSTR( remainder, 0, INSTR( remainder, ',' ) )
            ELSE
                remainder
        END AS element,
        CASE
            WHEN INSTR( remainder, ',' )>0 THEN
                SUBSTR( remainder, INSTR( remainder, ',' )+1 )
            ELSE
                NULL
        END AS remainder
    FROM list
    WHERE remainder IS NOT NULL
)
SELECT * FROM list;

(originally from this blog post: https://blog.expensify.com/2015/09/25/the-simplest-sqlite-common-table-expression-tutorial)

It produces:

element | remainder
-------------------
NULL    | 1,2,3,4,5
1       | 2,3,4,5
2       | 3,4,5
3       | 4,5
4       | 5
5       | NULL

the problem is thus to apply this to each row in a table.

Yes, a recursive common table expression is the solution:

with x(one, firstone, rest) as 
(select one, substr(many, 1, instr(many, ',')-1) as firstone, substr(many, instr(many, ',')+1) as rest from data where many like "%,%"
   UNION ALL
 select one, substr(rest, 1, instr(rest, ',')-1) as firstone, substr(rest, instr(rest, ',')+1) as rest from x    where rest like "%,%" LIMIT 200
)
select one, firstone from x UNION ALL select one, rest from x where rest not like "%,%" 
ORDER by one;

Output:

a|a1
a|a2
a|a3
b|b1
b|b3
c|c2
c|c1