简体   繁体   中英

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?

The fact that it returns anything at all is due to a quirk in MySQL. After all, what value should be returned for status ? It is not included in the GROUP BY . So, MySQL returns a value from an indeterminate row. 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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