mysql - 使用自连接的最大值

标签 mysql stored-procedures stored-functions

我有一个看起来像这样的表格...

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/

相关文章:

php - Yii 1.1.x CDbHttpSession 错误 : CDbConnection failed to open the DB connection: could not find driver

MySQL-获取条件数据

mysql - 需要 Laravel 查询帮助

sql - 如何在保持 0000 格式的 TEXT 中返回 DECIMAL(4,0)?

java - 调用返回值的存储函数的 JDBC 代码中出错

python - 在 Mac OS X Sierra 上为 Django Python 安装 mysqlclient

oracle - 如何使用 RefCursor 返回类型测试 Oracle 存储过程?

delphi - 使用 Delphi ADOStoredProc 从空结果集中获取列标题

c# - 如何在 ado.net 中执行表值函数?

postgresql - 错误消息 : Query has no destination for result data