Mysql中错误使用SQL语句Groupby被兼容的情况

首先创建数据库hncu,建立stud表格。

添加数据:

create table stud(
sno varchar(30) not null primary key,
sname varchar(30) not null,
age int,
saddress varchar(30)
);
insert into stud values('1001','tom',22,'湖南益阳');
insert into stud values('1002','jack',23,'益阳');
insert into stud values('1003','李白',22,'益阳');
insert into stud values('1004','王五',24,'中国北京');
insert into stud values('1005','张三',22,'益阳');
insert into stud values('1006','张四',23,'益阳');
insert into stud values('1007','李四',22,'湖南益阳');
insert into stud values('1008','刘备',24,'北京');

执行语句如下:

<喎�"/kf/ware/vc/" target="_blank" class="keylink">vcd4ncjxwcmugy2xhc3m9"brush:sql;"> select * from stud group by saddress;

显示了如下错误:

error 1055 (42000): expression #1 of select list is not in group by clause and contains nonaggregated column 'hncu.stud.sno' which is not functionally dependent
on columns in group by clause; this is incompatible with sql_mode=only_full_group_by

再执行此句:

select saddress as 平均年龄 from stud group by saddress;

-没有问题

然后我们用mysql,再执行前面那句错误的代码:

也就是:

select * from stud group by saddress;

我们看结果:

顺利的通过了,但是,你发现没有,前面的smo,sname,age,这3列的数据不对啊,没错,mysql强行显示第一次查找到的saddress不同的行了!!!其实这个结果是不对,但是mysql应该是兼容了这个错误!

而dos却是严格按照sql的语法来的。

sql的grop by 语法为,select 选取分组中的列+聚合函数 from 表名称 group by 分组的列

从语法格式来看,是先有分组,再确定检索的列,检索的列只能在参加分组的列中选。

所以问题中的,group by 后的 a,b,c是先确定的。select后的a,b,c才是可以变的。即

以下语句都是正确的:

select a,b,c from table_name group by a,b,c,d;
select a,b from table_name group by a,b,c;
select a,max(a) from table_name group by a,b,c;

以下语句则是错误的:

select a,b,c from table_name group by a,b;
select a,b,c from table_name group by a;

而因为mysql的强大,它兼容了这个错误!!!

但是在dos是不能的。所以出现了dos下报错,而在mysql中能够查找的情况(其实这个查找的结果是不对的)。

以上所述是www.887551.com给大家介绍的sql语句groupby在mysql中错误使用被兼容的情况,希望对大家有所帮助

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐