-1

我有 3 张桌子

comments(id,question_id, user_Id) // here the user_id is of the user who has asked the question
questions(id,q_desc, user_id)
users(id, name, rank)

用户可以提出问题并且可以对问题发表评论。

我需要一份报告,我想在其中显示最多 3 个排名靠前的用户的每个问题,他们对此发表了评论,但提出问题的用户不应该出现在该特定问题的报告中,但他也有有权评论他的问题。

已编辑:::

Select * from comments inner join users(comments.user_id=u.id) group by question_id order by user.rank desc
4

1 回答 1

4

它很乱,但它有效:

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上查看这两种解决方案的实际应用

于 2012-07-15T07:11:46.957 回答