MySQL:按最新的日期时间列排序?
MySQL: Order by newest datetime column?
这是我添加排序前的查询:
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'
有没有办法做我想做的事?
您可以加入,因此 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_data
在 collection_entries
中不超过一行。如果不是这种情况,那么您需要先 pre-aggregate。所以:
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;
这是我添加排序前的查询:
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'
有没有办法做我想做的事?
您可以加入,因此 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_data
在 collection_entries
中不超过一行。如果不是这种情况,那么您需要先 pre-aggregate。所以:
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;