多个 ORDER BY(获取最新元素)MySQL

Multiple ORDER BY (get latest element) MySQL

我有以下表格:收音机、播客和节目。收音机有很多播客,播客有很多节目。每个播客都可以按其历史排序,每个节目都可以按其 publication_date.

排序

我想获取与其最新节目相关的所有播客。

查询看起来像这样:

SELECT r.name AS radio_name,Pod.*,Sh.* 
FROM podcasts Pod 
  INNER JOIN radios r ON (r.id=Pod.radio_id) 
  INNER JOIN shows Sh ON (Sh.podcast_id=Pod.id) 
ORDER BY Pod.history LIMIT 5

我想要第二个 ORDER BY Sh.publication_date 但我真的不知道应该在哪里。

您可以在 order by 子句中使用逗号分隔多个表达式:

SELECT r.name AS radio_name,Pod.*,Sh.* 
FROM podcasts Pod 
  INNER JOIN radios r ON (r.id=Pod.radio_id) 
  INNER JOIN shows Sh ON (Sh.podcast_id=Pod.id) 
ORDER BY Pod.history, Sh.publication_date LIMIT 5
------------- Here -^

如果您只想要每个播客的最新节目,那么您需要一些东西来获取该信息。这是一种方法:

SELECT r.name AS radio_name,Pod.*,Sh.* 
FROM podcasts Pod INNER JOIN
     radios r
     ON r.id = Pod.radio_id INNER JOIN
     shows Sh
     ON Sh.podcast_id = Pod.id 
WHERE NOT EXISTS (select 1
                  from shows sh2
                  where sh2.podcast_id = sh.podcast_id.id and
                        sh2.publication_date > sh.publication_date
                 )
ORDER BY sh.publication_date DESC
LIMIT 5;

除了连接列上的 "obvious" 索引外,您还需要 shows(podcast_id, publication_date) 上的索引。

我还猜测您希望结果按最近的 显示 发布日期排序。