[英]Select MAX(timestamp) GROUP BY
I have the following table: 我有下表:
+----+----------+---------+--------+-------+---------------------+
| 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 |
+----+----------+---------+--------+-------+---------------------+
Why is the following query: 为什么下面的查询:
SELECT
order_id,
`status`,
MAX(timestamp)
FROM
order_status
GROUP BY
order_id
Returning the following result? 返回以下结果?
+----------+--------+---------------------+
| 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 |
+----------+--------+---------------------+
Shouldn't line 1 have status = 2? 第1行的状态不应该为2吗?
The fact that it returns anything at all is due to a quirk in MySQL. 它根本不返回任何东西的事实是由于MySQL中的一个古怪之处。 After all, what value should be returned for
status
? 毕竟,应该为
status
返回什么值? It is not included in the GROUP BY
. 它不包含在
GROUP BY
。 So, MySQL returns a value from an indeterminate row. 因此,MySQL从不确定行返回一个值。 Most other databases would simply return an error.
其他大多数数据库只会返回错误。
Try something like: 尝试类似:
select os.*
from order_status os
where timestamp = (select max(os2.time_stamp)
from order_status os2
where os2.order_id = os.order_id
);
This is very old but was my first result in google search when researching. 这是非常老的,但在研究时是我在Google搜索中的第一个结果。 You do not need a sub select, this is the correct way to solve this.
您不需要子选择,这是解决此问题的正确方法。
SELECT
DISTINCT (order_id),
status,
timestamp
FROM
order_status
ORDER BY order_id, timestamp DESC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.