不能再where后邊使用別名,group by后邊也一樣不能使用別名
select id,col1 - col2 from table1
where (col1 - col2) > 1000; —可以運行,但是不是很好看
嘗試
select id,(col1 - col2) as n1 from table1
where n1 > 1000; —會報錯,因為where后邊不能使用別名
如果篩選條件是個算式而且很長,總不能直接搬上吧
如何解決呢?
使用嵌套select
為什么where group by后邊不能用別名呢?(mysql中group by后邊可以用別名)
因為別名執行依附於select,而select的執行在where group by之后
所以不能用,在select執行操作后邊的操作可以用,比如order by limit等.
下面是執行順序
(7) SELECT
(8) DISTINCT <select_list>
(1) FROM <left_table>
(3) <join_type> JOIN <right_table>
(2) ON <join_condition>
(4) WHERE <where_condition>
(5) GROUP BY <group_by_list>
(6) HAVING <having_condition>
(9) ORDER BY <order_by_condition>
(10) LIMIT <limit_number>
我們發現select在第7位,where group by having 都是在select前面的,所以不能用別名.
注意:在使用where的時候后邊加的過濾字段不能是非聚合字段,而having后邊加的是聚合字段
因為where執行的順序是在group by之前,所以不能用聚合字段
where 和 having 可以同時使用,一個作用非聚合字段,一個作用聚合字段.
select t.id, t.n1 from(
select id,(col1 -col2) as n1 from table1
) e
where e.n1 > 1000;