【问题标题】:max value using self join使用自连接的最大值
【发布时间】:2013-04-15 07:33:46
【问题描述】:

我的桌子看起来像这样......

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);

【问题讨论】:

    标签: mysql stored-procedures stored-functions


    【解决方案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;
    

    【讨论】:

      【解决方案2】:

      我最后的信息是 MySQL 还不支持递归查询。 2011 年 12 月,this post 为此提到了 PostgreSQL 或 Sybase。

      您剩下的选择是从您的编程语言迭代 SQL 查询,直到获得空结果。

      【讨论】:

        【解决方案3】:

        最好增强您的架构以建立从任何订单到最新订单的链接。这通常使用所谓的传递闭包表来完成。

        您应该选择保持从任何订单到最新订单的链接持续(每次插入新订单时),或仅在需要时使用。这主要是一个以性能为导向的决定。在大多数情况下,传递闭包表会被持续维护。

        添加一个订单(或一组彼此之间不形成任何链的新订单)后,只需一条UPDATE 语句即可使用其先前值和新订单更新传递闭包表。

        从 MySQL 版本 5 开始,您可以在 billing_order_history 上使用触发器来更新传递闭包表(可以作为单独的表实现,也可以作为 billing_order_history 中的另一列实现)。

        【讨论】:

          猜你喜欢
          • 2020-08-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-07-25
          • 2016-03-15
          • 1970-01-01
          • 2010-12-24
          • 1970-01-01
          相关资源
          最近更新 更多