問題背景
1) 限制:每位使用者在一個類目下,最多享有4單滿送優惠。
即統計享受了滿送優惠的訂單數時需要排除掉同一類目下第四單以後的訂單
如何得到每個用戶同一類目下第四單ID呢?
select fourth(id) from order group by user_id, category;
可惜Mysql並沒有分組函數可以方便的得到每組中第四個id。但可以有變通方案, 如有如下的表
select * from t; +----+--------+----------------------------------+ | id | status | user_id | +----+--------+----------------------------------+ | 1 | 10 | 24e568a88fae11e6bb0650b497d97cdd | | 2 | 10 | 24e568a88fae11e6bb0650b497d97cdd | | 3 | 20 | 24e568a88fae11e6bb0650b497d97cdd | | 4 | 20 | 24e568a88fae11e6bb0650b497d97cdd | | 5 | 10 | e8669ac28fae11e6bb0650b497d97cdd | | 6 | 20 | e8669ac28fae11e6bb0650b497d97cdd | | 7 | 10 | e8669ac28fae11e6bb0650b497d97cdd | | 8 | 20 | e8669ac28fae11e6bb0650b497d97cdd | | 9 | 10 | e8669ac28fae11e6bb0650b497d97cdd | +----+--------+----------------------------------+
如何得到每位使用者第二次成功支付(status='10')的訂單呢?
方法一-- 逐一查詢
select * from t where user_id = '24e568a88fae11e6bb0650b497d97cdd' and status = '10' order by id limit 1,1; +----+--------+----------------------------------+ | id | status | user_id | +----+--------+----------------------------------+ | 2 | 10 | 24e568a88fae11e6bb0650b497d97cdd | +----+--------+----------------------------------+
方案二-- 一次性查詢
SELECT * FROM (SELECT id, user_id, @rank:=IF(@current_user_id = user_id, @rank + 1, 1) rank, @current_user_id:=user_id FROM (SELECT @current_user_id:=NULL, @rank:=NULL) vars, t WHERE t.status = '10' ORDER BY user_id , id) a WHERE rank = 2; +----+----------------------------------+------+----------------------------------+ | id | user_id | rank | @current_user_id:=user_id | +----+----------------------------------+------+----------------------------------+ | 2 | 24e568a88fae11e6bb0650b497d97cdd | 2 | 24e568a88fae11e6bb0650b497d97cdd | | 7 | e8669ac28fae11e6bb0650b497d97cdd | 2 | e8669ac28fae11e6bb0650b497d97cdd |
原理解釋
先按user_id和id順序順序,然後從11個開始分配順序號,並解釋
先按user_id和id順序順序,然後從11個開始分配順序號,同一用戶就遞增不同則重新從1開始。