简体   繁体   中英

mysql syntax query .difference between having and where what is the difference betw

create table employee(empid int,empname varchar(20),salary int, month varchar(20));
select empid,sum(salary) as total from employee group by empid **where** total>25000;

Why can't we use where in this program? Why is having key the only accepted thing?

To simplify: WHERE is used before a GROUP BY clause to filter the rows. HAVING is used after a GROUP BY and can access the "result" of the GROUP BY statement. See the documentation on the HAVING statement in SELECT statements :

The HAVING clause, like the WHERE clause, specifies selection conditions. The WHERE clause specifies conditions on columns in the select list, but cannot refer to aggregate functions. The HAVING clause specifies conditions on groups, typically formed by the GROUP BY clause. The query result includes only groups satisfying the HAVING conditions. (If no GROUP BY is present, all rows implicitly form a single aggregate group.)

That's why you can't access total in your sum(salary) as total expression with the WHERE clause, but can access it with the HAVING clause, which is applied after the result of sum(salary) is calculated and the GROUP BY clause is applied.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM