请教一下,对于像这样比较大的 sql 语句,有什么方法可以提升一下运行的效率吗?这个查询语句是用 AI 生成的,但是 AI 给出的优化好像也不明显,感觉还是好慢
WITH RECURSIVE TitleBlocks AS (
-- 第一层,找到所有超级块 B 里的标题块(一级标题)
SELECT b2.id, b2.content
FROM blocks AS b2
WHERE b2.type = 'h' -- 标题块
-------!!!!!【在这里修改需要汇总的书籍名字】!!!!!---------
AND b2.markdown LIKE '%# 《亲密关系》-米勒-目录%'-- 超级块 B 的条件
UNION ALL
-- 后续层级,找到所有子标题块(递归查找每个标题块的 parent_id)
SELECT b2.id, b2.content
FROM blocks AS b2
JOIN TitleBlocks AS tb ON b2.parent_id = tb.id -- 递归查找 parent_id
WHERE b2.type = 'h' -- 继续筛选标题块
),
-- 定义 CTE FilteredBlocks 用于筛选 type 为 'i' 且包含标题块内容的记录
FilteredBlocks AS (
SELECT b1.markdown
FROM blocks AS b1
JOIN TitleBlocks AS tb
ON b1.markdown LIKE '%' || tb.content || '%' -- 只匹配包含标题块内容的记录
WHERE b1.type = 'i' -- 筛选出 type 为 'i' 的块
AND b1.markdown NOT LIKE '%00-功能测试%'
),
-- 生成包含所有要统计类型的辅助表
Types AS (
SELECT '精彩文案' AS type
UNION ALL
SELECT '重要观点' AS type
UNION ALL
SELECT '内容讨论' AS type
UNION ALL
SELECT '内容有感' AS type
),
-- 统计精彩文案数量
GreatCopywritingCount AS (
SELECT
COUNT(*) AS count
FROM blocks AS bb
WHERE
bb.type = 'i'
AND bb.fcontent LIKE '%精彩文案%'
AND bb.markdown LIKE '%精彩文案%>%'
AND EXISTS (
-- 通过 EXISTS 查找 FilteredBlocks 中的匹配记录
SELECT 1
FROM FilteredBlocks fb
WHERE REPLACE(REPLACE(fb.markdown, '\n', ''), ' ', '') LIKE '%' || REPLACE(REPLACE(bb.markdown, '\n', ''), ' ', '') || '%'
)
),
-- 统计重要观点数量
ImportantOpinionCount AS (
SELECT
COUNT(*) AS count
FROM blocks AS bb
WHERE
bb.type = 'i'
AND bb.fcontent LIKE '%重要观点%'
AND bb.markdown LIKE '%重要观点%>%'
AND EXISTS (
-- 通过 EXISTS 查找 FilteredBlocks 中的匹配记录
SELECT 1
FROM FilteredBlocks fb
WHERE REPLACE(REPLACE(fb.markdown, '\n', ''), ' ', '') LIKE '%' || REPLACE(REPLACE(bb.markdown, '\n', ''), ' ', '') || '%'
)
),
-- 统计内容讨论数量
ContentDiscussionCount AS (
SELECT
COUNT(*) AS count
FROM blocks AS bb
WHERE
bb.type = 'i'
AND bb.fcontent LIKE '%内容讨论%'
AND bb.markdown LIKE '%内容讨论%>%'
AND EXISTS (
-- 通过 EXISTS 查找 FilteredBlocks 中的匹配记录
SELECT 1
FROM FilteredBlocks fb
WHERE REPLACE(REPLACE(fb.markdown, '\n', ''), ' ', '') LIKE '%' || REPLACE(REPLACE(bb.markdown, '\n', ''), ' ', '') || '%'
)
),
-- 统计内容有感数量
ContentReflectionCount AS (
SELECT
COUNT(*) AS count
FROM blocks AS bb
WHERE
bb.type = 'i'
AND bb.fcontent LIKE '%内容有感%'
AND bb.markdown LIKE '%内容有感%>%'
AND EXISTS (
-- 通过 EXISTS 查找 FilteredBlocks 中的匹配记录
SELECT 1
FROM FilteredBlocks fb
WHERE REPLACE(REPLACE(fb.markdown, '\n', ''), ' ', '') LIKE '%' || REPLACE(REPLACE(bb.markdown, '\n', ''), ' ', '') || '%'
)
)
SELECT
t.type AS 笔记类型,
COALESCE(
CASE
WHEN t.type = '精彩文案' THEN gcc.count
WHEN t.type = '重要观点' THEN ioc.count
WHEN t.type = '内容讨论' THEN cdc.count
WHEN t.type = '内容有感' THEN crc.count
ELSE 0
END,
0
) AS 笔记数量
FROM Types t
LEFT JOIN GreatCopywritingCount gcc ON t.type = '精彩文案'
LEFT JOIN ImportantOpinionCount ioc ON t.type = '重要观点'
LEFT JOIN ContentDiscussionCount cdc ON t.type = '内容讨论'
LEFT JOIN ContentReflectionCount crc ON t.type = '内容有感'
GROUP BY t.type;
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于