[英]Select MAX(timestamp) GROUP BY
我有下表:
+----+----------+---------+--------+-------+---------------------+
| id | order_id | user_id | status | notes | timestamp |
+----+----------+---------+--------+-------+---------------------+
| 3 | 1 | 0 | 0 | | 2015-11-29 22:49:44 |
| 4 | 1 | 0 | 2 | | 2015-11-29 22:51:51 |
| 5 | 2 | 0 | 0 | | 2015-11-29 23:14:26 |
| 6 | 3 | 0 | 0 | | 2015-11-29 23:15:52 |
+----+----------+---------+--------+-------+---------------------+
為什么下面的查詢:
SELECT
order_id,
`status`,
MAX(timestamp)
FROM
order_status
GROUP BY
order_id
返回以下結果?
+----------+--------+---------------------+
| order_id | status | MAX(timestamp) |
+----------+--------+---------------------+
| 1 | 0 | 2015-11-29 22:51:51 |
| 2 | 0 | 2015-11-29 23:14:26 |
| 3 | 0 | 2015-11-29 23:15:52 |
+----------+--------+---------------------+
第1行的狀態不應該為2嗎?
它根本不返回任何東西的事實是由於MySQL中的一個古怪之處。 畢竟,應該為status
返回什么值? 它不包含在GROUP BY
。 因此,MySQL從不確定行返回一個值。 其他大多數數據庫只會返回錯誤。
嘗試類似:
select os.*
from order_status os
where timestamp = (select max(os2.time_stamp)
from order_status os2
where os2.order_id = os.order_id
);
這是非常老的,但在研究時是我在Google搜索中的第一個結果。 您不需要子選擇,這是解決此問題的正確方法。
SELECT
DISTINCT (order_id),
status,
timestamp
FROM
order_status
ORDER BY order_id, timestamp DESC
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.