Is there a performance difference between HAVING on alias, vs not using HAVING

[亡魂溺海] 提交于 2019-12-11 07:09:56

问题


Ok, I'm learning, bit by bit, about what HAVING means.

Now, my question is if these two queries have difference performance characteristics:

Without HAVING

SELECT x + y AS z, t.*  FROM t
WHERE 
x = 1 and
x+y = 2

With HAVING

SELECT x + y AS z, t.*  FROM t
WHERE 
x = 1
HAVING
z = 2

回答1:


Yes it should be different - (1) is expected to be faster.

Having will ensure that first the main query is run and then the having filter is applied - so it basically works on a the dataset returned by the (query minus having).

The first query should be preferable, since it does not select those records at all.




回答2:


HAVING is used for queries that contain GROUP BY or return a single row containg the result of aggregate functions. For example SELECT SUM(scores) FROM t HAVING SUM(scores) > 100 returns either one row, or no row at all.

The second query is considered invalid by the SQL Standard and is not accepted by some database systems.



来源:https://stackoverflow.com/questions/4291280/is-there-a-performance-difference-between-having-on-alias-vs-not-using-having

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!