【问题标题】:Select 10 latest comments with unique author from MySQL table从 MySQL 表中选择 10 条具有唯一作者的最新评论
【发布时间】:2015-02-18 07:12:11
【问题描述】:

我的 MySQL 表包含以下列:comment_id、comment_content、comment_date、comment_author。 我需要获得 10 个具有唯一 comment_author 的最新 cmets。 这个查询:

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

几乎做我需要的,但它需要每个唯一作者的 1 条最旧的评论,但我需要最新的评论。尝试使用 GROUP BY cmets_author HAVING MAX(comment_date) 但没有任何改变。 谢谢。

【问题讨论】:

标签: mysql sql select group-by greatest-n-per-group


【解决方案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 和最大日期从主表中获取所需数据

【讨论】:

  • 您能否具体说明您的内部和整体查询是做什么的?它对即将到来的访客很有用。
【解决方案2】:

你可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多