问题背景
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顺序排序, 然后从1开始分配序号,同一用户就递增,不同用户则重新从1开始。
在线体验
http://sqlfiddle.com/#!9/ca126b/1