WhereandHaving区别
Where和Having的异同
创新互联,为您提供重庆网站建设公司、重庆网站制作、网站营销推广、网站开发设计,对服务成都汽车玻璃修复等多个行业拥有丰富的网站建设及推广经验。创新互联网站建设公司成立于2013年,提供专业网站制作报价服务,我们深知市场的竞争激烈,认真对待每位客户,为客户提供赏心悦目的作品。 与客户共同发展进步,是我们永远的责任!
(1)where是查询返回结果之前进行过滤的
(2)having是查询返回结果之后,对结果进行过滤的
(3)在SQL中增加 HAVING 子句原因是,where关键字无法与聚合函数一起使用,having子句常跟group by一同使用,过滤分组后的数据
测试表
MySQL> select * from t_order; +--------+---------+------------+------------+ | emp_no | dept_no | from_date | to_date | +--------+---------+------------+------------+ | 22744 | d006 | 1986-12-01 | 9999-01-01 | | 24007 | d005 | 1986-12-01 | 9999-01-01 | | 30970 | d005 | 1986-12-01 | 2017-03-29 | | 31112 | d002 | 1986-12-01 | 1993-12-10 | | 40983 | d005 | 1986-12-01 | 9999-01-01 | | NULL | d008 | 1986-12-01 | 1992-05-27 | | 48317 | d008 | 1986-12-01 | 1989-01-11 | | 49667 | d007 | 1986-12-01 | 9999-01-01 | | 50449 | d005 | 1986-12-01 | 9999-01-01 | | 10004 | d004 | 1986-12-01 | 9999-01-01 | +--------+---------+------------+------------+ 10 rows in set (0.00 sec)
Where后面如果提前使用列emp_no的别名aaa进行过滤的话,会报错列不存在,这是因为where字句是先对表进行过滤,才开始查询结果的
mysql> select emp_no as aaa from t_order where emp_no=22744; +-------+ | aaa | +-------+ | 22744 | +-------+ 1 row in set (0.00 sec) mysql> select emp_no as aaa from t_order where aaa=22744; ERROR 1054 (42S22): Unknown column 'aaa' in 'where clause'
Having后面可以跟列emp_no的原名或者别名aaa都可以,也可以跟group by,然后对分组后的聚合函数列进行筛选
mysql> select emp_no as aaa from t_order having emp_no=22744; +-------+ | aaa | +-------+ | 22744 | +-------+ 1 row in set (0.01 sec) mysql> select emp_no as aaa from t_order having aaa=22744; +-------+ | aaa | +-------+ | 22744 | +-------+ 1 row in set (0.00 sec) mysql> select dept_no,min(emp_no) aaa from t_order group by dept_no having aaa=31112; +---------+-------+ | dept_no | aaa | +---------+-------+ | d002 | 31112 | +---------+-------+ 1 row in set (0.00 sec)
网站名称:WhereandHaving区别
文章出自:http://cdiso.cn/article/gigsoi.html