1、在mysql中,group by中可以使用别名;where中不能使用别名;order by中可以使用别名。
mysql查询语句执行顺序是:
(1)FROM JOIN ON
(2)WHERE
(3)GROUP BY
(4)HAVING
(5)SELECT DISTINCT TOP()
(6)ORDER BY
所以在where执行的时候,别名还不存在,而order by的时候已经存在
因为sql是在where后order by前加别名,即生成结果集后加别名,where是在生成结果集前的操作,order by是生成结果集后的操作,因为where要生成结果集,而order by是对结果集的操作。如果非要用别名,那么只能用派生表,即先生成别名再where
select * from
(
select 字段1 as A,字段2 as B… from tablename
) aaa
where A=1
order by A
GROUP BY 和 ORDER BY 后使用别名
- 在MySQL中,GROUP BY 和 ORDER BY 可以使用别名,相当于把别名的语句放在 GROUP BY 和 ORDER BY 中,而 WHERE 中不能使用别名
- GROUP BY 和 ORDER BY 中使用别名时,赋值语句不会重复执行,只是将赋值语句的赋值顺序提前触发了
- 执行顺序为 GROUP BY => ORDER BY => SELECT 中的赋值语句
GROUP BY 后使用别名
select
case
when t.author_level in(1,2) then '1-2级'
when t.author_level in(3,4) then '3-4级'
when t.author_level in(5,6) then '5-6级'
else ''
end as level_cnt,
count(s.issue_id) as num
from author_tb t join answer_tb s on t.author_id = s.author_id
where s.char_len >= 100
group by level_cnt
order by num desc
等价于
select
case
when t.author_level in(1,2) then '1-2级'
when t.author_level in(3,4) then '3-4级'
when t.author_level in(5,6) then '5-6级'
else ''
end as level_cnt,
count(s.issue_id) as num
from author_tb t join answer_tb s on t.author_id = s.author_id
where s.char_len >= 100
group by
case
when t.author_level in(1,2) then '1-2级'
when t.author_level in(3,4) then '3-4级'
when t.author_level in(5,6) then '5-6级'
else ''
end
order by num desc
2、在oracle中:
1)where/group by/having子句中只能直接使用栏位或者常量,而不能使用栏位的别名,除非这个别名来自子查询之中,如:select …. from (select col1 ccc from table) where ccc > 1
2)而order by 则可以直接使用别名,如select col1 ccc from table order by ccc
这和sql 的执行顺序是有关的,where中的部分先执行 -> 如果有group by,接着执行group by -> select中的函数计算、别名指定再运行-> 最后order by
因此,字段、表达式的别名在where子句和group by子句都是不能使用的,而在order by中不仅可以使用别名,甚至可以直接使用栏位的下标来进行排序,如:order by 1 desc,2 asc