前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Sql实战-分组查询排序后取出前n条记录

Sql实战-分组查询排序后取出前n条记录

作者头像
小土豆Yuki
发布2023-10-30 17:13:24
1900
发布2023-10-30 17:13:24
举报
文章被收录于专栏:洁癖是一只狗洁癖是一只狗
  • 查询分组内某个分组对应的所有记录

代码语言:javascript
复制
CREATE TABLE `products` (
`id` int(11) NOT NULL,
`name` varchar(100) DEFAULT NULL,
`category` varchar(100) DEFAULT NULL,
`type` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
代码语言:javascript
复制
INSERT INTO `products` VALUES
('1', 'Apple', 'Fruit', '1'), 
('2', 'Banana', 'Fruit', '1'), 
('3', 'Carrot', 'Vegetable', '2'), 
('4', 'Tomato', 'Vegetable', '2'), 
('5', 'Chicken', 'Meat', '3'), 
('6', 'Beef', 'Meat', '4')

GROUP_CONCAT函数可以将每个分组内的数据连接起来,形成一个字符串,按照分类和类型进行分组,使用group_concat知道组内的所有记录id

代码语言:javascript
复制
select  category,type,GROUP_CONCAT(id) as ids from
products GROUP BY category,type;

查找分组内某个分组内的所有记录,如category='Fruit' 且 type='1' 对应的所有记录

代码语言:javascript
复制
select  a.*  from  products a inner join (
select  category,type from products where category ='Fruit'
and type='1' GROUP BY category,type
) b on a.category=b.category and a.type=b.type
  • 分组内最大的一条记录(常用)
代码语言:javascript
复制
select  *  from  products a  where
exists (
   select 1 from products  where
   a.category=category and a.id>id )
代码语言:javascript
复制
select  *  from  products a where a.id in 
(select MAX(id) from products GROUP BY category)
  • 分组内前N条记录(如获取某个学生考试分数前2的记录)
代码语言:javascript
复制
select *  from  students a where exists 
(select count(1) from students where name=a.name and score>a.score 
 having count(1)<2) order by a.name

分析,拿到a表某个学生的数据,和子查询比较,找到比a表的这个学生分数大的数量小于2的,就认为这个分数是前2名了,就会拿到每个学生的前2名分数了

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2023-10-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 洁癖是一只狗 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档