建表语句
CREATE TABLE `test22` (
`id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`tel` varchar(255) DEFAULT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
插入语句
INSERT INTO `my_taobao`.`test22`(`id`, `name`, `tel`) VALUES (2, 'a', 'a2');
INSERT INTO `my_taobao`.`test22`(`id`, `name`, `tel`) VALUES (1, 'a', 'a1');
INSERT INTO `my_taobao`.`test22`(`id`, `name`, `tel`) VALUES (3, 'b', 'b1');
INSERT INTO `my_taobao`.`test22`(`id`, `name`, `tel`) VALUES (4, 'b', 'b2');
INSERT INTO `my_taobao`.`test22`(`id`, `name`, `tel`) VALUES (7, 'c', 'c3');
INSERT INTO `my_taobao`.`test22`(`id`, `name`, `tel`) VALUES (5, 'c', 'c1');
INSERT INTO `my_taobao`.`test22`(`id`, `name`, `tel`) VALUES (6, 'c', 'c2');
表数据
id | name | tel |
---|---|---|
2 | a | a2 |
1 | a | a1 |
3 | b | b1 |
4 | b | b2 |
7 | c | c3 |
5 | c | c1 |
6 | c | c2 |
Group By不包含所有的非聚合字段
select id,name,tel from test22 GROUP BY name;
查询结果:
id | name | tel |
---|---|---|
2 | a | a2 |
3 | b | b1 |
7 | c | c3 |
结论
该查询sql在执行的时候,先根据name字段进行group by分组,然后对每一个group by的集合进行limit 1操作,得到最终的结果集。