我有一个mysql表articles
,其中的内容按以下层次结构组织:
剖面图
主题
第章
岗位
上面的每一项都在一行中,具有以下字段:id
、parent
、name
等。
后行parent
等于章节行id
,章节行parent
等于主题行id
,主题行parent
等于章节行id
。
我没有比上面更高的等级。
我需要选择给定部分中的主题列表以及每个主题的所有子项的计数。计数是子章节及其子章节(即文章)的数量之和。
我哥哥帮我做了以下选择查询。然而,它在~0.6秒时相对较慢。
SELECT
subjects.id,
subjects.name,
subjects.link,
(
SELECT
COUNT(DISTINCT posts.id)
FROM
articles AS chapters,
articles AS posts
WHERE
chapters.parent = subjects.id AND(
posts.parent = chapters.id OR posts.parent = subjects.id
)
) AS child_count
FROM
articles AS subjects
WHERE
subjects.parent = 62
我需要帮助来提高成绩。
谢谢!啊!
最佳答案
这个逻辑很难理解,但我认为你打算:
SELECT s.id, s.name, s.link,
( (SELECT COUNT(*) -- count children
FROM articles c
WHERE c.parent = s.id
) +
(SELECT COUNT(*) -- count grandchildren
FROM articles c JOIN
articles p
ON p.parent = c.id
WHERE c.parent = s.id
)
) as child_count
FROM articles s
WHERE s.parent = 62;
然后对于这个查询,您需要
articles(parent)
上的索引。笔记:
不要在
FROM
子句中使用逗号。始终使用正确、明确、标准的
JOIN
语法。你弟弟还需要学习如何编写正确的sql。COUNT(DISTINCT)
可能比COUNT()
更贵。correlation or
OR
子句中的ON
s可能会妨碍优化器。关于mysql - 选择MySQL中所有子行的计数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56911028/