首先創(chuàng)建數(shù)據(jù)庫hncu,建立stud表格。
添加數(shù)據(jù):
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,'北京');
執(zhí)行語句如下:
<喎?"/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxwcmUgY2xhc3M9"brush:sql;"> SELECT * FROM stud GROUP BY saddress;
顯示了如下錯(cuò)誤:
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 dependenton columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
再執(zhí)行此句:
SELECT saddress as 平均年齡 FROM stud GROUP BY saddress;
-沒有問題
然后我們用MySQL,再執(zhí)行前面那句錯(cuò)誤的代碼:
也就是:
SELECT * FROM stud GROUP BY saddress;
我們看結(jié)果:
順利的通過了,但是,你發(fā)現(xiàn)沒有,前面的smo,sname,age,這3列的數(shù)據(jù)不對啊,沒錯(cuò),MySQL強(qiáng)行顯示第一次查找到的saddress不同的行了?。?!其實(shí)這個(gè)結(jié)果是不對,但是MySQL應(yīng)該是兼容了這個(gè)錯(cuò)誤!
而DOS卻是嚴(yán)格按照SQL的語法來的。
SQL的grop by 語法為,select 選取分組中的列+聚合函數(shù) 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;
以下語句則是錯(cuò)誤的:
select a,b,c from table_name group by a,b;select a,b,c from table_name group by a;
而因?yàn)镸ySQL的強(qiáng)大,它兼容了這個(gè)錯(cuò)誤!??!
但是在DOS是不能的。所以出現(xiàn)了DOS下報(bào)錯(cuò),而在MySQL中能夠查找的情況(其實(shí)這個(gè)查找的結(jié)果是不對的)。
以上所述是小編給大家介紹的SQL語句Groupby在MySQL中錯(cuò)誤使用被兼容的情況,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時(shí)回復(fù)大家的。在此也非常感謝大家對VeVb武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選