繁体   English   中英

选择MAX(时间戳)GROUP BY

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM