我有表,看起來像這樣...最大值加入
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
我需要給原來的順序編號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);