【问题标题】:How to reuse a recursive WITH clause in SQLite?如何在 SQLite 中重用递归 WITH 子句?
【发布时间】:2020-10-24 01:45:04
【问题描述】:

我有一个很好的递归 WITH 子句:

WITH RECURSIVE split(seq, word, str) AS (
        SELECT 0, null, replace('name+one+two+three.jpg', '.jpg', '+')
        UNION ALL SELECT
            seq+1,
            substr(str, 0, instr(str, '+')),
            substr(str, instr(str, '+')+1)
        FROM split WHERE str != ''
    ) SELECT word FROM split where seq>1

输出是:

one
two
three

现在,我怎样才能重用这个子句,应用SELECT name from Images 代替那个常量字符串'name+one+two+three.jpg'

目标是提取可以在整个图像名称集中找到的所有唯一“+后缀”字符串。例如,这是示例数据:

DROP TABLE IF EXISTS ImagesTemp;
CREATE TEMP TABLE ImagesTemp (name );
INSERT INTO ImagesTemp (name)
VALUES
  ('IMG_0403+newport+malboro+kool.jpg'),
  ('IMG_0404+camel+newport.JPG'),
  ('IMG_0405+dunhill+doral+malboro.png');
SELECT * from ImagesTemp

预期的输出是:

word    count
malboro 2
newport 2
kool    1
dunhill 1
doral   1
camel   1

【问题讨论】:

  • 发布样本数据和预期结果以澄清。

标签: sql sqlite common-table-expression recursive-query


【解决方案1】:

考虑将 CTE 的锚点替换为表中的选择,如下所示:

WITH RECURSIVE split(seq, word, str) AS (
    SELECT 0, null, replace(name, '.jpg', '+')
    FROM images
    UNION ALL 
    SELECT
        seq+1,
        substr(str, 0, instr(str, '+')),
        substr(str, instr(str, '+')+1)
    FROM split 
    WHERE str != ''
) 
SELECT word FROM split WHERE seq>1

【讨论】:

  • 我首先尝试过,但它使“DB Browser for SQLite”挂起。在内部选择语句中添加 LIMIT 10000 可以防止查询挂起,尽管我不相信结果。但是谢谢你指出我的解决方案。
【解决方案2】:

想通了!这里的技巧是确保文件名以“+”结尾,这样递归子句就可以在不挂起的情况下工作。我还添加了文件扩展名计数。

WITH RECURSIVE split(seq, word, str, filename) AS (
    SELECT 0, null, lower(replace(name, '.', '+.')||'+'), name from ImagesTemp
    UNION ALL 
    SELECT
        seq+1,
        substr(str, 0, instr(str, '+')),
        substr(str, instr(str, '+')+1),
        filename
    FROM split 
    WHERE str != ''
) 
SELECT distinct word, count(*) as count, filename as sample
FROM split WHERE word != '' and seq>1
GROUP BY word
ORDER BY count DESC

结果:

word    count   sample
newport 2   IMG_0403+newport+malboro+kool.jpg
malboro 2   IMG_0403+newport+malboro+kool.jpg
.jpg    2   IMG_0404+camel+newport.JPG
kool    1   IMG_0403+newport+malboro+kool.jpg
dunhill 1   IMG_0405+dunhill+doral+malboro.png
doral   1   IMG_0405+dunhill+doral+malboro.png
camel   1   IMG_0404+camel+newport.JPG
.png    1   IMG_0405+dunhill+doral+malboro.png

【讨论】:

    猜你喜欢
    • 2017-12-16
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多