我们前几篇学习的是DQL的编写语句,那么DQL的执行顺序是什么呢?
执行顺序
- 编写顺序(SFWGHOL):SELECT … FROM … WHERE … GROUP BY … HAVING … ORDER BY … LIMIT …
- 执行顺序(FWGHSOL):FROM … WHERE … GROUP BY … HAVING … SELECT … ORDER BY … LIMIT …
接下来验证一下:
数据库:world(MySQL自带),数据表:city(MySQL自带)
-- where
select countrycode as cc, name as nm from city
where name like 'a%'
order by countrycode; -- 正常执行
select countrycode as cc, name as nm from city
where nm like 'a%' -- 换成别名
order by countrycode; -- 报错
-- group by
select countrycode as cc, avg(population) as avg_populaiton from city
group by countrycode
order by countrycode; -- 正常执行
select countrycode as cc, avg(population) as avg_populaiton from city
group by cc -- 换成别名
order by countrycode; -- 报错
-- order by
select countrycode as cc, name as nm from city
where name like 'a%'
order by cc; -- 换成别名,正常执行
- where和group by使用别名时会报错!因为它们在select之前执行!order by使用别名则不会报错!
- Error Code: 1054. Unknown column 'nm' in 'where clause'
- MySQL中做了优化,group by后面使用别名,程序不会报错。
不总结=白学
THE END