2012-07-15 139 views
-1

前3名评论员我有3个表获取从表中MySQL查询

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 
+0

@书呆子,追风见行动这两个解决方案:我没加我的查询,然后,因为我有在启动该问题,因为问题出在前三排用户为各问题 – 2012-07-15 05:53:30

回答

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; 

这些解决方案还可以解决已发布mor的用户而不是同一问题中的一条评论。

SQLFiddle

+0

优秀的赞恩,我接受你的答案,你可以请帮我在层次结构问题 http://stackoverflow.com/questions/11064913/achieve-hierarchy-in-a-less-number-of-mysql-查询 – 2012-07-15 07:39:10

+0

@SashiKant,谢谢!顺便说一下,如果您有兴趣,我只是提出了一个更简洁的解决方案。看修改后的答案。 – 2012-07-15 07:40:05

+0

::帽子花花公子 – 2012-07-15 07:48:21