Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 12th, 2012  |  syntax: None  |  size: 1.57 KB  |  hits: 7  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Get the top 3 commentator from a table in mysql query
  2. comments(id,question_id, user_Id) // here the user_id is of the user who has asked the question
  3. questions(id,q_desc, user_id)
  4. users(id, name, rank)
  5.        
  6. Select * from comments inner join users(comments.user_id=u.id) group by question_id order by user.rank desc
  7.        
  8. SELECT
  9.     a.question_id, a.user_id, a.name, a.rank
  10. FROM
  11. (
  12.     SELECT a.*, b.name, b.rank
  13.     FROM
  14.     (
  15.         SELECT DISTINCT b.question_id, b.user_id
  16.         FROM questions a
  17.         INNER JOIN comments b ON a.id = b.question_id AND a.user_id <> b.user_id
  18.     ) a
  19.     INNER JOIN users b ON a.user_id = b.id
  20. ) a
  21. INNER JOIN
  22. (
  23.     SELECT a.question_id, b.rank
  24.     FROM
  25.     (
  26.         SELECT DISTINCT b.question_id, b.user_id
  27.         FROM questions a
  28.         INNER JOIN comments b ON a.id = b.question_id AND a.user_id <> b.user_id
  29.     ) a
  30.     INNER JOIN users b ON a.user_id = b.id
  31. ) b ON a.question_id = b.question_id AND a.rank <= b.rank
  32. GROUP BY
  33.     a.question_id, a.user_id, a.name, a.rank
  34. HAVING
  35.     COUNT(1) <= 3
  36. ORDER BY
  37.     a.question_id, a.rank DESC
  38.        
  39. SELECT a.*
  40. FROM
  41. (
  42.    SELECT DISTINCT a.question_id, a.user_id, b.name, b.rank
  43.    FROM comments a
  44.    INNER JOIN users b ON a.user_id = b.id
  45. ) a
  46. INNER JOIN
  47.     questions b ON a.question_id = b.id AND a.user_id <> b.user_id
  48. INNER JOIN
  49. (
  50.    SELECT DISTINCT a.question_id, a.user_id, b.rank
  51.    FROM comments a
  52.    INNER JOIN users b ON a.user_id = b.id
  53. ) c ON b.id = c.question_id AND a.rank <= c.rank
  54. GROUP BY
  55.     a.question_id, a.user_id, a.name, a.rank
  56. HAVING
  57.     COUNT(1) <= 3
  58. ORDER BY
  59.     a.question_id, a.rank DESC;