您好,登錄后才能下訂單哦!
Where和Having的異同
(1)where是查詢返回結(jié)果之前進(jìn)行過濾的
(2)having是查詢返回結(jié)果之后,對結(jié)果進(jìn)行過濾的
(3)在SQL中增加 HAVING 子句原因是,where關(guān)鍵字無法與聚合函數(shù)一起使用,having子句常跟group by一同使用,過濾分組后的數(shù)據(jù)
測試表
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進(jìn)行過濾的話,會(huì)報(bào)錯(cuò)列不存在,這是因?yàn)閣here字句是先對表進(jìn)行過濾,才開始查詢結(jié)果的
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,然后對分組后的聚合函數(shù)列進(jìn)行篩選
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)
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。