问题
I know this is much discussed, but none of my research could convince me the difference between 'where
' and 'having
' clauses in MySQL. From what I understand we can achieve everything that can be done with 'where' clause using 'having
' . For eg. select * from users having username='admin'
. Then why do you need 'where
' clause? Does using where make any performance differences?
回答1:
The WHERE
clause filters data from the source before aggregates, whereas HAVING
clause filters data after the GROUP BY
has been applied. Generally this means any non-aggregate filter can appear in either place, but if you have a column that is not referenced in your query, you can only filter it in a WHERE
clause.
For example, if you have the following table:
| ID | VALUE |
--------------
| 1 | 15 |
| 2 | 15 |
| 3 | 20 |
| 4 | 20 |
| 5 | 25 |
| 6 | 30 |
| 7 | 40 |
Suppose you wanted to apply the following query:
select value, count(value)
from Table1
group by value
But you only wanted to include rows where ID > 2
. If you put that in a HAVING
clause, you will get an error, because the ID
column is not available post aggregate as it is not in the SELECT
clause. In that case, you would be required to use a WHERE
clause instead:
select value, count(value)
from Table1
where id > 2
group by value
Demo: http://www.sqlfiddle.com/#!2/f6741/16
回答2:
The difference between HAVING
from WHERE
clause is that HAVING
supports aggregated columns while WHERE
doesn't because it is only applicable for individual rows., EG
SELECT ID
FROM tableName
GROUP BY ID
HAVING COUNT(ID) > 1 --- <<== HERE
From the MySQL docs,
"You may use Alias's if you use HAVING instead of WHERE this is one of the defined differences between the two clauses. Having is also slower and will not be optimized, but if you are placing a complex function like this in your where you obviously aren't expecting great speed."
回答3:
Where evaluates on the single row level, whereas having is used for group by expressions.
回答4:
With the HAVING
clause, you can specify a condition to filter groups as opposed to filtering individual
rows, which happens in the WHERE
phase.
Only groups for which the logical expression in the HAVING
clause evaluates to TRUE are returned by the HAVING
phase . Groups for which the logical expression evaluates to FALSE or UNKNOWN
are filtered out.
When GROUP BY
is not used, HAVING
behaves like a WHERE
clause .
Regarding performance comparison please see this article
来源:https://stackoverflow.com/questions/15090342/why-do-you-have-where-when-there-is-having