- 查询分组内某个分组对应的所有记录
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
- 分组内最大的一条记录(常用)
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的记录)
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名分数了