我的桌子看起来像这样......
mysql> select * from billing_order_history;
+----------+---------------+--------------+---------------------+
| order_id | modify_action | new_order_id | modified_by_user_id |
+----------+---------------+--------------+---------------------+
| 52 | 2 | 54 | 1 |
| 54 | 2 | 55 | 1 |
| 55 | 2 | 56 | 1 |
+----------+---------------+--------------+---------------------+
3 rows in set (0.00 sec)
旧订单 ID 连接到新订单 ID。52 >> 54 >> 55 >> 56
给定原始订单 ID 52,我需要返回最新的订单 ID,即 56。
如果我在 where 子句中添加 b.order_id = 52,我已经编写了以下自联接。
select max(a.new_order_id) from billing_order_history as a inner join billing_order_history as b on a.order_id = b.new_order_id
模式和样本记录:
CREATE TABLE billing_order_history (
order_id bigint(20) ,
modify_action int(11) ,
new_order_id bigint(20) ,
modified_by_user_id bigint(20)
) ;
insert into billing_order_history values (52, 2, 54, 1), (54, 2, 55, 1), (55,2,56,1);