SQL中的where和having:
where表示在语句中需要的条件限制。
Persons 表:
Id | LastName | FirstName | Address | City |
---|---|---|---|---|
1 | Adams | John | Oxford Street | London |
2 | Bush | George | Fifth Avenue | New York |
3 | Carter | Thomas | Changan Street | Beijing |
where语法: select 字段名 from 表名 where 字段名 运算符 值;
运算符包括:=、<>(!=)、<、>、<=、>=、between ....and、link
例1:select * from Persons where FirstName="John"; //查询Persons 中的FirstName字段为John的所有数据
例1执行结果为:1 Adams John OxfordStreet London
例2: select * from Persons where FirstName link "T%"; //查询Persons中的FirstName值以T开始的所有数据
例2执行结果为:2 Bush George Fifth Avenue New York
having一般与合计函数联合使用。
我们拥有下面这个 "Orders" 表:
O_Id | OrderDate | OrderPrice | Customer |
---|---|---|---|
1 | 2008/12/29 | 1000 | Bush |
2 | 2008/11/23 | 1600 | Carter |
3 | 2008/10/05 | 700 | Bush |
4 | 2008/09/28 | 300 | Bush |
5 | 2008/08/06 | 2000 | Adams |
6 | 2008/07/21 | 100 | Carter |
having例句:查询订单少于2000的客户
select Customer ,sum(OrderPrice) from Orders group by Customer having sum(OederPrice)<2000;
解释(从后面向前面翻译):查询OederPrice和少于2000的客户,以Customer的值分组,在Orders里面查;
上句查询结果:Carter 1700
总结:其实where和having都是在查询的时候添加条件,但是where不能与合计函数联合使用,而having可以。有having就必须有group by ;有group by 不一定有having。