Group By 有哪些注意事項(xiàng)?你知道嗎?
注意:本文以下內(nèi)容基于 MySQL 5.7 InnoDB 數(shù)據(jù)庫(kù)引擎。
1、group by 后面不能加 where
在 MySQL 中,所有的 SQL 查詢語(yǔ)法要遵循以下語(yǔ)法順序:
- select
- from
- where
- group by
- having
- order by
- limit
以上語(yǔ)法順序是不能前后互換的,否則報(bào)錯(cuò)。比如我們不能在 group by 之后添加 where 查詢語(yǔ)句,否則會(huì)出現(xiàn)如下錯(cuò)誤:
語(yǔ)法順序的執(zhí)行是和 MySQL 的 select 語(yǔ)句執(zhí)行順序相關(guān)的,select 執(zhí)行先后順序如下:
- from 階段
- where 階段
- group 階段
- having 階段
- select 階段
- order by 階段
- limit 階段
注意:其中 select 比較特殊,在進(jìn)行查詢語(yǔ)句編寫(xiě)時(shí),要寫(xiě)在最前面,其余語(yǔ)法順序要和執(zhí)行先后順序保持一致。
2、having 或 group by 可單獨(dú)使用
having 和 group by 可以單獨(dú)使用,如下查詢所示:
3、having 和 group by 可使用別名
當(dāng) having 單獨(dú)使用時(shí),它的作用和 where 類(lèi)似,但又有細(xì)微的不同。比如在 where 中不能使用別名,但 having 和 group by 卻可以別名。咱們創(chuàng)建一個(gè)測(cè)試表來(lái)演示一下,建表 SQL 如下:
drop table if exists student_score;
create table student_score(
id int primary key auto_increment comment '主鍵',
name varchar(250) comment '姓名',
math decimal(4,1) comment '數(shù)學(xué)成績(jī)',
chinese decimal(4,1) comment '語(yǔ)文成績(jī)'
);
insert into student_score(name,math,chinese) values('張三',50,50),('李四',80,80),('王五',90,90);
表中的數(shù)據(jù)如下圖所示:
當(dāng)我們使用總成績(jī)別名 total 分別在 where 和 having 中使用時(shí),查詢結(jié)果如下:
從上述結(jié)果可以看出,having 查詢可以使用 select 中的別名,而 where 不能使用別名。
除了 having 可以使用別名之外,group by 也可以使用別名,如下圖所示:
為什么where不能用別名?為having卻可以?
where 中不能使用別名,這和 MySQL 語(yǔ)句執(zhí)行順序有關(guān),MySQL 語(yǔ)句執(zhí)行順序如下:
- from 階段
- where 階段
- group 階段
- having 階段
- select 階段
- order by 階段
- limit 階段
也就是說(shuō),在執(zhí)行 where 查詢時(shí),select 還沒(méi)執(zhí)行,因此在 where 中想要使用還未執(zhí)行的 select 中的別名是不行的。那從上面的執(zhí)行順序可以看到,having 執(zhí)行也在 select 之前,為什么它就可以使用 select 中的別名呢?
這是因?yàn)?MySQL 在 5.7.5 之后做了擴(kuò)展,允許在 having 中使用別名,官方文檔中有相應(yīng)的說(shuō)明,如下圖所示:
MySQL 官方文檔地址:
https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html。
PS:group by 能使用別名的原理和 having 類(lèi)似。
總結(jié)
SQL 語(yǔ)句編寫(xiě)一定要遵循此先后順序:select、from、where、group by、having、order by、limit。其中 having 或 group by 都可單獨(dú)使用,并且在 MySQL 5.7.5 之后,group by 和 having 可以使用別名查詢,但 where 不能使用別名。