学习group by遇到的问题
表,id为主键
±—±---------±----------±--------------------±-----------+
| id | LastName | FirstName | Address | City |
±—±---------±----------±--------------------±-----------+
| 1 | Adams | John | Oxford Street | London |
| 2 | Bush | George | Fifth Avenue | New York |
| 3 | Carter | Thomas | Changan Street | Beijing |
| 4 | Obama | Barack | Pennsylvania Avenue | Washington |
±—±---------±----------±--------------------±-----------+
1、
select id,Address,City,FirstName from people GROUP BY City;
报错信息
select id,Address,City,FirstName from people GROUP BY City
1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column ‘liuqing.people.id’ which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
查询时间: 0s
2、
select Address,City,FirstName from people GROUP BY City,FirstName,Address;
结果:
3、
select Address,City,FirstName from people GROUP BY id;
结果:
4、
select id,Address,City,FirstName from people GROUP BY id,Address,City,FirstName;
结果:
通过对比以上4种结果,发现要想group by可以分组就要
1、使其前面的字段和后面的字段都有
2、group by后面主键’id‘
3、前后都有主键字段值
满足以上三个任意,才会支持sql语句group by的条件。
注意,第一个语句的报错sql_mode=only_full_group_by,需要满足sql的规定:
select @@GLOBAL.sql_mode;
select @@SESSION.sql_mode;