我正在创建一个博客系统,我想获得帖子评论。注释有一个多级树,但我只使用一个表来保存所有。
您是否知道获得5条评论的最佳语法以及您的孩子的评论(回复)?
如果我需要将回复的数量限制为5,例如,我如何只在一个查询中执行此操作?
答案 0 :(得分:2)
在blog_comments
表格上使用自我加入。此查询将提供5个最新的博客文章以及一个后代的所有子女。
SELECT t1.id AS parentID, t2.id AS childID, t1.content AS parentContent,
t2.content AS childContent
FROM
(
SELECT id, content
FROM blog_comments
ORDER BY creation_date DESC
LIMIT 5
) t1
INNER JOIN blog_comments t2
ON t1.id = t2.parent
ORDER BY t1.id, t2.id
<强>更新强>
我更喜欢以下查询,该查询显示了最近的五篇博文,每篇博文都在自己的行上,后面跟着所有的子回复。这更类似于您希望在应用层中显示的内容。
SELECT
CASE WHEN t.childId = -1 THEN 'parent' ELSE 'child' END AS type,
t.content
FROM
(
SELECT childId, parentId, content FROM
(
SELECT -1 AS childId, id AS parentId, content AS content
FROM blog_comments
WHERE parent IS NULL
ORDER BY creation_date DESC
LIMIT 5
) t1
UNION ALL
SELECT t1.id AS childId, t1.parent AS parentId, t1.content AS content
FROM blog_comments t1
INNER JOIN
(
SELECT id
FROM blog_comments
WHERE parent IS NULL
ORDER BY creation_date DESC
LIMIT 5
) t2
ON t1.parent = t2.id
) t
ORDER BY t.parentId, t.childId
以下是正在运行的演示的链接: