GROUP BY并获得前两排

时间:2015-08-21 11:22:26

标签: mysql sql subquery

所以我有以下查询,它按照我的预期进行。它从每个aothor获得最新发表的文章。但是现在我希望它能从每位作者那里得到最新的两篇文章。我怎么能这样做?

SELECT author_article.ID
FROM (
       SELECT
         sorted_articles.ID,
         sorted_articles.AuthorID,
         sorted_articles.PublishedDate
       FROM ArticlePage sorted_articles
       ORDER BY PublishedDate DESC
     ) author_article
GROUP BY author_article.AuthorID
ORDER BY author_article.PublishedDate DESC;

enter image description here

所以我需要的是每位作者的最新2篇文章。

3 个答案:

答案 0 :(得分:3)

使用相关的子查询来统计同一作者的所有最新文章。如果最近有一篇或更少的文章,请返回该行。

SELECT *
FROM ArticlePage t1
WHERE (select count(*) from ArticlePage t2
       where t2.AuthorID = t1.AuthorID
         and t2.PublishedDate > t1.PublishedDate) <= 1

答案 1 :(得分:1)

如果你想要作者和文章ID,那么这将把它们放在一行:

SELECT ap.AuthorId,
       SUBSTRING_INDEX(GROUP_CONCAT(ap.AuthorId ORDER BY ap.PublishedDate DESC
                                   ), ',', 2) as Top2Articles
FROM ArticlePage ap
GROUP BY ap.AuthorId;

注意:组concat中间值的默认长度是有限的,但如果某些作者有很多很多很多文章,则可以更改。

此外,您的原始查询正在使用MySQL的(错误)功能,该功能明确记录为不能按预期工作。您SELECT中的列不在GROUP BY中。这些值来自 indeterminate 行,因此子查询中的ORDER BY可能不会以您想要的方式影响结果。

答案 2 :(得分:1)

给出row_number只是另一个观点。

<强>查询

select t2.articleId,
t2.articleName,
t2.authorName,
t2.publishedDate
from
(
   select articleId,
   articleName,
   authorName,
    publishedDate,
    ( 
        case authorName 
        when @curA
        then @curRow := @curRow + 1 
       else @curRow := 1 and @curA := authorName end
    ) + 1 as rn
    from article t,
    (select @curRow := 0, @curA := '') r
    order by authorName,publishedDate desc
)t2
where t2.rn<3;

Fiddle demo

相关问题