1. 程式人生 > >Where和having

Where和having

where基於from的資料做的篩選;

(個人理解)having基於select的資料做的篩選

按照以上的理解,可以做以下測試:

表名student,列名及資料:

+------+--------+------+------+| SId  | Sname  | Sage | Ssex | +------+--------+------+------+ | 1    | 張三   | 18   | 男   | | 2    | 李四   | 20   | 男   | | 3    | 王武   | 22   | 男   | | 4    | 小白   | 20   | 女   | +------+--------+------+------+

mysql> select * from student a where a.Sage > 20; +------+--------+------+------+ | SId  | Sname  | Sage | Ssex | +------+--------+------+------+ | 3    | 王武   | 22   | 男   | +------+--------+------+------+ 1 row in set (0.00 sec)

mysql> select * from student a having a.Sage > 20; +------+--------+------+------+ | SId  | Sname  | Sage | Ssex | +------+--------+------+------+ | 3    | 王武   | 22   | 男   | +------+--------+------+------+

mysql> select a.Sname from student a having a.Sage > 20; ERROR 1054 (42S22): Unknown column 'a.Sage' in 'having clause'

錯誤原因:select中沒有Sage欄位

mysql> select max(a.Sage) as ma from student a where ma > 20; ERROR 1054 (42S22): Unknown column 'ma' in 'where clause'

錯誤原因:where 後不能使用select中的別名或聚合行數

mysql> select max(a.Sage) as ma from student a having ma > 20; +------+ | ma   | +------+ | 22   | +------+ 1 row in set (0.00 sec)