Mysql 派生 table 排序依据

Mysql derived table order by

如果我运行下面的查询:

SELECT *
FROM `smp_data_log`
WHERE Post_id = 1234 AND Account_id = 1306
ORDER BY Created_time DESC

我返回 7 行,包括具有以下内容的条目 Created_times:

1) 1424134801

2) 1424134801

3) 1421802001

4) 3601

如果我运行下面的查询:

SELECT mytable.*
FROM (SELECT * FROM `smp_data_log` ORDER BY Created_time DESC) AS mytable
WHERE Post_id = 1234 AND Account_id = 1306
GROUP BY Post_id

我希望看到 1424134801 作为一行返回 - 但我看到的是 3601??我原以为这会返回最近的时间(下降)。我做错了什么?

你的期望是错误的。这在 MySQL 中有详细记录。您正在使用扩展,其中 select 中有列 group by 中没有的列 - 这是一个非常糟糕的习惯,并且在其他数据库中不起作用(除非在某些非常特殊的情况下ANSI 标准允许)。

只需使用 join 即可获得您真正想要的:

SELECT l.*
FROM smp_data_log l JOIN
     (select post_id, max(created_time) as maxct
      from smp_data_log
      group by post_id
     ) lmax
     on lmax.post_id = l.post_id and lmax.maxct = l.created_time;

引用自documentation

MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause. This means that the preceding query is legal in MySQL. You can use this feature to get better performance by avoiding unnecessary column sorting and grouping. However, this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate.