如何找到下一个订单id mysql

ldxq2e6h  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(372)

样本输入

order_id Customer_id Order_date    
1          1         2017-11-01    
2          2         2017-11-02    
3          1         2017-11-03    
4          2         2017-11-04

期望输出

order_id next_order_id

1              3    
2              4    
3    
4
rjjhvcjd

rjjhvcjd1#

你也可以 subquery :

SELECT order_id, 
       (select order_id 
        from table 
        where Customer_id = t.Customer_id and 
              Order_date > t.Order_date
        order by Order_date 
        LIMIT 1) as next_order_id
FROM table t
ORDER BY order_id;
41ik7eoe

41ik7eoe2#

你可以用 LEAD :

SELECT order_id,
 LEAD(order_id) OVER(PARTITION BY Customer_id ORDER BY Order_date) AS next_order
FROM tab
ORDER BY order_id;

dbfiddle演示-mysql 8.0
对于以前的mysql版本:

SELECT order_id,
     (SELECT order_id 
     FROM tab t2 
     WHERE t1.customer_id = t2.customer_id 
       and t2.Order_date > t1.order_date 
     ORDER BY Order_date LIMIT 1 ) AS next_order
FROM tab t1
ORDER BY order_id;

D小提琴演示2

oxcyiej7

oxcyiej73#

mysql中的规范方法是关联子查询:

select t.*,
       (select t2.order_id
        from t t2
        where t2.customer_id = t.customer_id and t2.order_date > t.order_date
        order by t2.order_date desc
        limit 1
       ) as next_order_id
from t;

如果您使用的是mysql 8.0,那么 lead() 是更好的选择。

相关问题