mysql 按某个字段分组,然后取每组前3条记录
比如我有一表,我要按channelId来分组,然后取每一组的前三条记录,sql该怎么写,高手帮忙解决下...
比如我有一表,我要按channelId来分组,然后取每一组的前三条记录,sql该怎么写,高手帮忙解决下
展开
若以下回答无法解决问题,邀请你更新回答
1个回答
展开全部
CREATE TABLE test (
channelId int,
subChanID INT
);
INSERT INTO test
SELECT 1, 11 UNION ALL
SELECT 1, 12 UNION ALL
SELECT 1, 13 UNION ALL
SELECT 1, 14 UNION ALL
SELECT 1, 15 UNION ALL
SELECT 2, 21 UNION ALL
SELECT 2, 22 UNION ALL
SELECT 2, 23 UNION ALL
SELECT 2, 24 UNION ALL
SELECT 2, 25;
SELECT
*
FROM
test main
WHERE
(SELECT COUNT(1)
FROM test sub
WHERE
main.channelId = sub.channelId
AND main.subChanID > sub.subChanID
) < 3;
+-----------+-----------+
| channelId | subChanID |
+-----------+-----------+
| 1 | 11 |
| 1 | 12 |
| 1 | 13 |
| 2 | 21 |
| 2 | 22 |
| 2 | 23 |
+-----------+-----------+
6 rows in set (0.00 sec)
这个效果可以么?
channelId int,
subChanID INT
);
INSERT INTO test
SELECT 1, 11 UNION ALL
SELECT 1, 12 UNION ALL
SELECT 1, 13 UNION ALL
SELECT 1, 14 UNION ALL
SELECT 1, 15 UNION ALL
SELECT 2, 21 UNION ALL
SELECT 2, 22 UNION ALL
SELECT 2, 23 UNION ALL
SELECT 2, 24 UNION ALL
SELECT 2, 25;
SELECT
*
FROM
test main
WHERE
(SELECT COUNT(1)
FROM test sub
WHERE
main.channelId = sub.channelId
AND main.subChanID > sub.subChanID
) < 3;
+-----------+-----------+
| channelId | subChanID |
+-----------+-----------+
| 1 | 11 |
| 1 | 12 |
| 1 | 13 |
| 2 | 21 |
| 2 | 22 |
| 2 | 23 |
+-----------+-----------+
6 rows in set (0.00 sec)
这个效果可以么?
追问
太感谢了,不过完全不懂意思,能跟我说下吗
追答
你去看那个参考资料的帖子了么?
如果上面的 SQL , 你不怎么看得懂, 那么下面这样的写法,与执行结果,应该能让你更加容易明白一些上面的SQL的处理的原理。
SELECT
channelId ,
subChanID ,
(SELECT COUNT(1)
FROM test sub
WHERE
main.channelId = sub.channelId
AND main.subChanID > sub.subChanID
) AS 有多少行数据subChanID比当前行小
FROM
test main
参考资料: http://hi.baidu.com/wangzhiqing999/blog/item/46903f55aa5143818d543069.html
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询