好的,SO挖掘的时间,我仍然找到了一个解决方案 - 一个IMO相当明显 - 的任务。我有posts
,我想在每个帖子(最新的)中查询最多 5 comments
。
所以基本上是这样的:
SELECT p.id, p.title, c.id, c.text
FROM posts p
LEFT JOIN comments c ON p.id = c.postId LIMIT 5
(伪,不起作用)
如何限制加入?
答案 0 :(得分:2)
SELECT *
FROM posts p
LEFT JOIN
comments c
ON c.post_id = p.id
AND c.id >=
COALESCE(
(
SELECT ci.id
FROM comments ci
WHERE ci.post_id = p.id
ORDER BY
ci.post_id DESC, ci.id DESC -- You need both fields here for MySQL to pick the right index
LIMIT 4, 1
), 0
)
在comments (post_id)
或comments (post_id, id)
(如果comments
为MyISAM)上创建索引,以便快速开展此工作。
答案 1 :(得分:2)
这看起来像[greatest-n-per-group]问题。该链接指向此站点上的其他标记问题。我会首先获取您的所有帖子/评论,然后您可以将其限制为每个帖子的最近5个,如下所示:
SELECT p1.*, c1.*
FROM posts p1
LEFT JOIN comments c1 ON c1.post_id = p1.id
WHERE(
SELECT COUNT(*)
FROM posts p2
LEFT JOIN comments c2 ON c2.post_id = p2.id
WHERE c2.post_id = c1.post_id AND c2.commentDate >= c1.commentDate
) <= 5;
这是关于该主题的另一个reference。
答案 2 :(得分:0)
您可以使用变量:
SELECT pid, title, cid, text
FROM (
SELECT p.id AS pid, p.title, c.id AS cid, c.text,
@row_number:= IF(@pid = p.id,
IF (@pid:=p.id, @row_number+1, @row_number+1),
IF (@pid:=p.id, 1, 1)) AS rn
FROM posts p
CROSS JOIN (SELECT @row_number := 0, @pid := 0) AS vars
LEFT JOIN comments c ON p.id = c.postId
ORDER BY p.id ) t <-- add comments ordering field here
WHERE t.rn <= 5