我有一个看起来像这样的表格...
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,即原始订单 ID 52 的 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);
最佳答案
你可以试试这个:
select max(latest)
from (
Select @latest:=case when @latest=order_id then new_order_id else @latest end
as latest from billing_order_history, (select @latest:=55 ) as t
order by order_id) as t1;
关于mysql - 使用自连接的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16009898/