group by学习

 

执行语句select brand as 品牌,carid as 数量 from car group by brand;报错

ERROR 1055 (42000): Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'car.car.carid' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

mysql8中可以使用group by

select @@sql_mode可以查看数据库模式:ONLY_FULL_GROUP_BY

该语句的功能是统计:不同品牌车数量;

如果带有ONLY_FULL_GROUP_BY,在使用group by时,select列表的列必须存在于group by中,或者是聚集函数。如果禁用了ONLY_FULL_GROUP_BY则没有这个限制。

因此解决方法有两种:

1. 修改语句成select brand as 品牌,count(carid) as 数量 from car group by brand;执行结果如下:

+-------------------+--------+
| 品牌              | 数量   |
+-------------------+--------+
| 保时捷            |   1002 |
| 法拉利            |    968 |
| 宝马              |    992 |
| 大众              |   1029 |
| 丰田              |    958 |
| 阿斯顿·马丁       |    984 |
| 奥迪              |    981 |
| 本田              |   1013 |
| 奔驰              |   1050 |
| 迈凯伦            |   1023 |
+-------------------+--------+
10 rows in set (0.01 sec)

2. 禁用ONLY_FULL_GROUP_BY选项,禁用方法可以搜索解决。

你可能感兴趣的:(数据库)