Frage

I have table that looks something like this...

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)

Old Order ID is connected to new order ID. 52 >> 54 >> 55 >> 56

I need to return the latest order ID i.e. 56 given the original order ID 52.

I have written the following self join that does not work if I add b.order_id = 52 in the where clause.

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 

Schema and sample records:

 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);
War es hilfreich?

Lösung

you can try this:

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;

Andere Tipps

My last information was that MySQL does not yet support recursive queries. December 2011, this post referred to either PostgreSQL or Sybase for that.

Your remaining option is to iterate the SQL query from your programming language until you get an empty result.

It is good to enhance your schema to establish a link from any order to the newest order. This is usually done using a so called transitive closure table.

You should choose between maintaining the link from any order to the newest order continuously (every time you insert new orders), or only when you need to use it. This is primarily a performance oriented decision. In most circumstances, the transitive closure table would be continuously maintained.

After adding one order (or a set of new orders that do not form any chain among themselves), one needs only a single UPDATE statement to update the transitive closure table using its previous value and the new orders.

Starting with MySQL Version 5 you can use triggers on billing_order_history to update the transitive closure table (which can be implemented either as a separate table, or as another column in billing_order_history).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top