在操作sql 查詢數(shù)據(jù)的時候有時候會遇到查詢每一個用戶第一次干嘛或者第幾次干嘛的數(shù)據(jù)宇葱,這個時候往往第一想到的是group by鲜屏,這邊介紹一種不采用group by的實(shí)現(xiàn)方式罕扎,首先介紹一下我的表和數(shù)據(jù):
CREATE TABLE `orderTable` (
`num` int(11) DEFAULT NULL, --數(shù)據(jù)id
`userId` varchar(255) DEFAULT NULL, -- 用戶id
`name` varchar(255) DEFAULT NULL, --用戶名稱
`time` datetime DEFAULT NULL, --時間
`tag` int(3) DEFAULT '0' --標(biāo)記(驗(yàn)證查詢數(shù)據(jù)結(jié)果正確性)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
和表內(nèi)的數(shù)據(jù)
INSERT INTO `orderTable` VALUES (1, '001', 'u001', '2019-06-08 21:48:54', 1);
INSERT INTO `orderTable` VALUES (2, '001', 'u001', '2019-06-29 21:49:16', 2);
INSERT INTO `orderTable` VALUES (3, '002', 'u002', '2019-06-06 21:49:38', 1);
INSERT INTO `orderTable` VALUES (4, '001', 'u001', '2019-06-30 21:49:58', 3);
INSERT INTO `orderTable` VALUES (5, '002', 'u002', '2019-06-30 21:50:21', 2);
INSERT INTO `orderTable` VALUES (6, '003', 'u003', '2019-06-03 21:50:50', 1);
INSERT INTO `orderTable` VALUES (7, '003', 'u003', '2019-06-05 21:51:06', 2);
INSERT INTO `orderTable` VALUES (8, '004', 'u004', '2019-06-20 21:51:26', 1);
INSERT INTO `orderTable` VALUES (9, '001', 'u001', '2019-07-02 21:53:06', 4);
現(xiàn)在要查找出每一個用戶的第二次交易的數(shù)據(jù)
select t.*
from (
select
if(@last = t.userId, @gnum, @gnum := @gnum + 1) as gnum,
if(@last <> t.userId, @rnum := 1, @rnum := @rnum + 1) as rnum,
@last := t.userId,
'||',
t.*
from
(select @gnum := 0, @rnum := 1, @last := '') p,
orderTable t
ORDER BY t.userId, t.time
) t
where t.rnum = 2
原理是通過ORDER BY對數(shù)userId和time進(jìn)行排序,再為每行數(shù)據(jù)添加上gnum(group number)和group內(nèi)rnum(row number)沪么,再結(jié)合通過這兩個編號進(jìn)行數(shù)據(jù)過濾。