mysql中group by 兼容问题

首先建立数据库hncu,创建stud表格。
添加数据:sql

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,'北京');
  •  

执行语句以下:数据库

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
  •  

再执行此句:this

SELECT saddress as 平均年龄 FROM stud GROUP BY saddress;
  •  

-没有问题
.net

而后咱们用MySQL,再执行前面那句错误的代码:
也就是:code

SELECT * FROM stud GROUP BY saddress;
  •  

咱们看结果:
get

顺利的经过了,可是,你发现没有,前面的smo,sname,age,这3列的数据不对啊,没错,MySQL强行显示第一次查找到的saddress不一样的行了!!!其实这个结果是不对,可是MySQL应该是兼容了这个错误!
而DOS倒是严格按照SQL的语法来的。it

SQL的grop by 语法为,
select 选取分组中的列+聚合函数 from 表名称 group by 分组的列
从语法格式来看,是先有分组,再肯定检索的列,检索的列只能在参加分组的列中选。io

因此问题中的,group by 后的 a,b,c是先肯定的。select后的a,b,c才是能够变的。即table

如下语句都是正确的:

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中可以查找的状况(其实这个查找的结果是不对的)。

总结起来一句话就是,检索里的东西必定要出如今group by里先,select的东西要先出如今group by里

相关文章
相关标签/搜索