我的问题是:
我的桌子是MESSAGE
和MESSAGE_COMMENT
,
MESSAGE (id,content)
MESSAGE_COMMENT (id, message_id, content)
我需要为每个消息选择所有消息和最多3条评论,如本例所示:
type | id | content
M 15 "this is a message with no comments"
M 16 "this is another message with many comments"
R 16 "comment1"
R 16 "comment2"
R 16 "comment3"
M 17 "this is another message with no comments"
“id”是消息时的
MESSAGE.id
,是评论时的COMMENT.message_id
。我希望我已经清楚地解释了我的问题。。
最佳答案
SELECT *
FROM (
SELECT m.id,
COALESCE(
(
SELECT id
FROM message_comment mc
WHERE mc.message_id = m.id
ORDER BY
mc.message_id DESC, id DESC
LIMIT 2, 1
), 0) AS mid
FROM message m
) mo
LEFT JOIN
message_comment mcd
ON mcd.message_id >= mo.id
AND mcd.message_id <= mo.id
AND mcd.id >= mid
在
message_comment (message_id, id)
上创建索引以使其快速工作。请参阅我的博客中的这篇文章,以获取有关其工作原理的更详细解释:
Advanced row sampling