Skip to content

Instantly share code, notes, and snippets.

@limingxinleo
Last active March 9, 2022 05:02
Show Gist options
  • Save limingxinleo/d1a267a73c83d9c35d6c06a723ff3b7c to your computer and use it in GitHub Desktop.
Save limingxinleo/d1a267a73c83d9c35d6c06a723ff3b7c to your computer and use it in GitHub Desktop.
MySQL 分组查询前两条
# reply 表中,以 reply 分组,并查询每个分组 id 最小的前 2 条
SELECT r.*
FROM reply r
WHERE r.reply_id IN (1, 2)
AND 2 >= (
SELECT COUNT(*)
FROM reply
WHERE reply_id = r.reply_id
AND id <= r.id
)
ORDER BY r.reply_id, id;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment