SQL中,where 与 having 的性能比较

时间:2023-01-24 19:20:12

原文:http://blog.csdn.net/showshore/article/details/7263115

---------------------------------------------------------

在做项目的过程中,使用sql语句时,很多时候会用到where或having。

看到国外一个论坛上有人提到两者性能比较的这个问题时,有人是这样回答的:

The theory (by theory I mean SQL Standard) says that WHERE restricts the result set before returning rows and HAVING restricts the result set after bringing all the rows. So WHERE is faster. On SQL Standard compliant DBMSs in this regard, only use HAVING where you cannot put the condition on a WHERE (like computed columns in some RDBMSs.)

也就是说(从理论上讲),where是在查询前做条件限制,having是在查询后的结果集上做条件限制。

查询前做限制的话,返回的件数会少;而在查询后的结果集上做限制的话,之前的查询结果可能会很多,这样就会影响性能。

所以,一般是用where,having是在where不方便或者不能使用的情况下才使用。