2014-12-19 74 views
2

我已經得到了與這樣的列的MySQL表:comment_id,comment_content,comment_date,comment_author。 我需要得到10個具有獨特comment_author的最新評論。 這個查詢:從MySQL表選擇10個最新評論與獨特作者

SELECT comment_content, comment_date, comment_author 
FROM comments 
GROUP BY comment_author 
ORDER BY comment_date DESC 
LIMIT 10 

幾乎做什麼,我需要,但它需要從每一個獨特的作家1個最古老的評論,但我需要最新的一個。嘗試使用GROUP BY comments_author HAVING MAX(comment_date),但沒有任何更改。 謝謝。

+0

也許這可能對您有幫助嗎? :http://stackoverflow.com/questions/14770671/mysql-order-by-before-group-by – 2014-12-19 11:01:10

+0

您的查詢似乎是完美的。 – 2014-12-19 11:01:18

+1

@ jQuery.PHP.JAVA.net我們對完美有很不同的定義 – Strawberry 2014-12-19 11:04:08

回答

1

您可以使用left join實現這一

select 
c1.comment_content, 
c1.comment_date, 
c1.comment_author 
from comments c1 
left join comments c2 on c1.comment_author = c2.comment_author 
and c1.comment_date < c2.comment_date 
where c2.comment_author is null 
order by c1.comment_date desc limit 10 
+0

謝謝,完美的作品 – Tropos 2014-12-21 15:43:06

1

試試這個:

SELECT c.comment_content, c.comment_date, c.comment_author 
FROM comments c 
INNER JOIN (SELECT comment_author, MAX(comment_date) AS comment_date 
      FROM comments 
      GROUP BY comment_author 
      ) A ON c.comment_author = A.comment_author AND c.comment_date = A.comment_date 
ORDER BY c.comment_date DESC 
LIMIT 10; 
  1. 提取記錄與最新的日期的所有COMMENT_AUTHOR所以請我的內層查詢。
  2. 然後通過加入comment_author和最大日期從主表中獲取所需的數據
+0

您能指定一下您的內在和整體查詢嗎?它適用於即將到來的訪問者。 – 2014-12-19 11:29:12

+1

這個作品也很完美:) – Tropos 2014-12-21 19:32:12