它很乱,但它有效:
SELECT
a.question_id, a.user_id, a.name, a.rank
FROM
(
SELECT a.*, b.name, b.rank
FROM
(
SELECT DISTINCT b.question_id, b.user_id
FROM questions a
INNER JOIN comments b ON a.id = b.question_id AND a.user_id <> b.user_id
) a
INNER JOIN users b ON a.user_id = b.id
) a
INNER JOIN
(
SELECT a.question_id, b.rank
FROM
(
SELECT DISTINCT b.question_id, b.user_id
FROM questions a
INNER JOIN comments b ON a.id = b.question_id AND a.user_id <> b.user_id
) a
INNER JOIN users b ON a.user_id = b.id
) b ON a.question_id = b.question_id AND a.rank <= b.rank
GROUP BY
a.question_id, a.user_id, a.name, a.rank
HAVING
COUNT(1) <= 3
ORDER BY
a.question_id, a.rank DESC
编辑:这会产生相同的结果并且更简洁:
SELECT a.*
FROM
(
SELECT DISTINCT a.question_id, a.user_id, b.name, b.rank
FROM comments a
INNER JOIN users b ON a.user_id = b.id
) a
INNER JOIN
questions b ON a.question_id = b.id AND a.user_id <> b.user_id
INNER JOIN
(
SELECT DISTINCT a.question_id, a.user_id, b.rank
FROM comments a
INNER JOIN users b ON a.user_id = b.id
) c ON b.id = c.question_id AND a.rank <= c.rank
GROUP BY
a.question_id, a.user_id, a.name, a.rank
HAVING
COUNT(1) <= 3
ORDER BY
a.question_id, a.rank DESC;
这些解决方案还考虑了在同一问题中发布了多个评论的用户。
在SQLFiddle上查看这两种解决方案的实际应用