
Untitled
By: a guest on
Aug 12th, 2012 | syntax:
None | size: 1.57 KB | hits: 7 | expires: Never
Get the top 3 commentator from a table in mysql query
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)
Select * from comments inner join users(comments.user_id=u.id) group by question_id order by user.rank desc
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;