【问题标题】:MySQL: Order by newest datetime column?MySQL:按最新的日期时间列排序?
【发布时间】:2020-11-05 16:05:25
【问题描述】:

这是我添加排序之前的查询:

SELECT `picture` 
FROM `profile_data` 
WHERE `profile_id` IN (
    SELECT `profile_id` FROM `collection_entries` WHERE `collection_id` = 2
) 
LIMIT 10;

我尝试像这样添加排序:

SELECT `picture` 
FROM `profile_data` 
WHERE `profile_id` IN (
    SELECT `profile_id` 
    FROM `collection_entries` 
    WHERE `collection_id` = 2 
    ORDER BY `created_at` DESC
) 
LIMIT 10;

虽然我收到了这个问题:

This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'

有什么方法可以做我想做的事吗?

【问题讨论】:

  • IN() 子句中的排序没有用处。

标签: mysql sql subquery sql-order-by inner-join


【解决方案1】:

您可以改为加入,因此created_at 列可在外部查询中用于排序:

SELECT `picture` 
FROM `profile_data` pd
INNER JOIN `collection_entries` ce ON ce.`profile_id` = pd.`profile_id`
WHERE ce.`collection_id` = 2
ORDER BY ce.`created_at` DESC
LIMIT 10;

这假设每个profile_datacollection_entries 中不超过一行。如果不是这种情况,那么您需要先进行预聚合。所以:

SELECT `picture` 
FROM `profile_data` pd
INNER JOIN (
    SELECT `profile_id`, MAX(`created_at`) `created_at`
    FROM `collection_entries` 
    WHERE `collection_id` = 2
    GROUP BY `profile_id`
) ce ON ce.`profile_id` = pd.`profile_id`
ORDER BY ce.`created_at` DESC
LIMIT 10;

【讨论】:

  • 我以为 Gordon 是这个网站上唯一的 SQL 机器。我错了 +1。
  • @TimBiegeleisen:我确实认为这是一种恭维......谢谢!
猜你喜欢
  • 2012-12-03
  • 2013-10-28
  • 1970-01-01
  • 1970-01-01
  • 2010-12-01
  • 1970-01-01
  • 2011-12-01
  • 1970-01-01
  • 2016-01-31
相关资源
最近更新 更多