如何从表中获取最大ID?

时间:2019-04-29 09:46:58

标签: mysql sql select

我有一个表order_status_history,用于存储详细信息状态历史记录。表结构和数据以图像以及文本格式显示。这里是PK。

order_status_history table

id  date        status  order_id    updated_by
1   11/12/2018  WAI         1       12365
2   11/12/2018  ACT         1       12365
3   11/12/2018  DEL         1       12365
4   11/12/2018  WAI         3       12365
5   11/12/2018  ACT         3       12365
6   11/12/2018  DEL         3       12365
7   11/12/2018  WAI         4       12365
8   11/12/2018  ACT         5       12365
9   11/12/2018  WAI         4       12365
10  11/12/2018  WAI         5       12365
11  11/12/2018  ACT         5       12365
12  11/13/2018  DEL         5       12365
13  11/13/2018  WAI         6       12365
14  11/13/2018  WAI         6       12365
15  11/13/2018  WAI         6       12365

我需要获取具有最大id的所有行,其中状态是特定日期范围内每个订单ID的WAI。所需的样本输出在图像的黄色背景中,以及在下面的文本格式中。

id  date        status  order_id    updated_by
1   11/12/2018  WAI         1       12365
4   11/12/2018  WAI         3       12365
9   11/12/2018  WAI         4       12365
10  11/12/2018  WAI         5       12365
15  11/13/2018  WAI         6       12365

2 个答案:

答案 0 :(得分:1)

您可以联接一个派生表,该表在聚合中的每个订单的状态为'WAI',以获取最大ID。

SELECT t1.*
       FROM elbat t1
            INNER JOIN (SELECT max(t2.id) id
                               FROM elbat t2
                               WHERE t2.status = 'WAI'
                               GROUP BY t2.order_id) x
                       ON x.id = t1.id;

答案 1 :(得分:0)

您可以使用相关子查询:

select t.*
from table t
where t.id = (select max(t1.id) from table t1 where t1.order_id = t.order_id and t1.status = 'WAI');