Py学习  »  DATABASE

mysql:sort,使行在列a之后聚集在一起,而组在列b中对应的最大值之后进行排序

Johannes Lemonde • 6 年前 • 1544 次点击  

对于一个虚拟示例,假设我有一个包含以下行的数据库: book , author (=A列) publish-date (=B列)。

现在,我想对这些书进行分类,这样行就由作者组合在一起了,但是作者必须以这样的顺序出现:最近出版的作者排在第一位。每一位作者的书必须按出版日期分类。

输出示例:

BOOK            AUTHOR          PUBLISH-DATE    # COMMENT
some book       John Doe        2019            # most recent book => John Doe is first
another book    John Doe        2017
one more        John Doe        2011
again a book    Richard Roe     2016            # Richard Roe is second because this is the most recent book amongst the remaining ones.
and one more    Richard Roe     2008            
another one     Janie Doe       2013            # and so on.

(以上例子的解释:多伊之所以排在第一位,是因为他最近写了一本书。但他其他的书都是紧接着展出的,按出版日期倒序排列。接下来是理查德·罗,因为他是最近出版一本书的第二位作家。等等。)

基本上,不是用 ORDER BY author ASC, publish-date DESC ,我想在第三列中的最大值之后,重新排列给定作者的书籍组。

我不知道如何在mysql中解决这个问题,也不知道如何调用这种排序。我希望你能帮助我^提前谢谢!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/39693
文章 [ 2 ]  |  最新文章 6 年前
forpas
Reply   •   1 楼
forpas    6 年前

您必须先按每个作者的最新发布日期排序,然后按发布日期降序排列:

select b.*
from books b
order by (
  select max(publishdate)
  from books
  where author = b.author
) desc, b.publishdate desc
Gordon Linoff
Reply   •   2 楼
Gordon Linoff    6 年前

一种方法是关联子查询:

select t.*
from t
order by (select max(t2.publish_date)
          from t t2
          where t2.author = t.author
         );

mysql 8+(和标准sql)使用窗口函数有一个简单得多的方法:

select t.*
from t
order by max(publish_date) over (partition by author)