MySQL数据库入门——where子句,组合where的子句

select语句的where子句指定搜索条件过滤显示的数据。


1)使用where子句

在 select 语句中,where子句在from子句之后给出,返回满足指定搜索条件的数据:

select prod_name, prod_price from Products where prod_price = 3.49;

#从Products表中检索两个列:prod_name,和prod_price,但条件是只显示prod_price值为3.49的行。


除了上述例子的相等条件判断,where子句还支持以下条件操作符:
clip_image001

例如,使用<>操作符(或!=)进行不匹配检查

select vend_id, prod_name from Products where vend_id <> 'DLL01';

#从Products表中显示vend_id,和prod_name ,但条件是vend_id不是DLL01。


再如,使用between操作符可匹配处于某个范围内的值。需要指定范围的端点值:

select prod_name, prod_price from Products where prod_price between 5.99 and 9.49;

# 从Products表中显示prod_name, prod_price,但是条件是价格在5.99美元和9.49美元之间 (包括5.99美元和9.49美元)


2)组合where子句

(1SQL还允许使用and或or操作符组合出多个where子句,例如使用and操作符:

select prod_id, prod_price, prod_name from Products where vend_id = 'DLL01' AND prod_price <= 4;

#从Products表中显示 prod_id, prod_price和prod_name,但是条件是vend_id为DLL01和prod_price小于等于4(两个条件必须全部满足)


(2同理,可使用OR操作符检索匹配任一条件的行:

select prod_name, prod_price from Products where vend_id = 'DLL01' OR vend_id = 'BRS01';

#从Products表中显示prod_name和prod_price,但是条件是vend_id为DLL01或者是vend_id为BRS01(只需满足任一条件即可)


(3)求值顺序

where子句允许包含任意数目的and和or操作符以进行复杂、高级的过滤。但需要注意求值顺序:and操作符优先级高于or操作符,但可以使用圆括号明确地指定求值顺序:

select prod_name, prod_price from Products where (vend_id = 'DLL01' or vend_id ='BRS01') and prod_price <= 10;

#从Products表中显示prod_name和prod_price,但是条件是(vend_id为DLL01或者是vend_id为BRS01)同时prod_price小于等于10


4IN操作符

IN操作符用来指定条件范围,范围中的每个条件都可以进行匹配。条件之间用逗号分隔:

select prod_name, prod_price from Products where vend_id in ( 'DLL01', 'BRS01' ) order by prod_name;

#从Products表中显示prod_name和prod_price,但是条件是(vend_id为DLL01和vend_id为BRS01)按照 prod_name排序。

注:IN操作符完成了与OR相同的功能,但与OR相比,IN操作符有如下优点:
- 有多个条件时,IN操作符比一组OR操作符更清楚直观且执行得更快;
- 在与其他AND和OR操作符组合使用IN时,求值顺序更容易管理;
- IN操作符的最大优点是可以包含其他SELECT语句,能动态地建立WHERE子句。


5NOT操作符

NOT操作符用来否定跟在它之后的条件:

select vend_id,prod_name from Products where not vend_id = 'DLL01' order by prod_name;

#从Products表中显示 vend_id和prod_name ,但是条件是除了vend_id为DLL01,按照 prod_name排序。


上面的例子也可以使用<>操作符来完成。但在更复杂的子句中,NOT是非常有用的。例如,在与IN操作符联合使用时,NOT可以非常简单地找出与条件列表不匹配的行:

select vend_id,prod_name from Products where vend_id not in ( 'DLL01', 'BRS01' ) order by prod_name;

#从Products表中显示 vend_id和prod_name ,但是条件是除了vend_id为DLL01,按照 prod_name排序。

注:和多数其他 DBMS允许使用 NOT 对各种条件取反不同,MySQL支持使用 NOT 对 IN 、 BETWEEN 和EXISTS子句取反。


(6LIKE操作符

使用LIKE操作符和通配符可以进行模糊搜索,以便对数据进行复杂过滤。最常使用的通配符是百分号( % ),它可以表示任何字符出现任意次数:

select prod_id, prod_name from Products where prod_name like '%bean bag%';

#从Products表中显示 prod_id和prod_name ,但是条件是prod_name的行中含有[bean bag]字段的数据。


另一个有用的通配符是下划线(_)。它的用途与%一样,但只匹配单个字符,而不是多个或0个字符:

select prod_id, prod_name from Products where prod_name like '_ inch teddy bear';

#从Products表中显示 prod_id和prod_name ,但是条件是prod_name的行中含有[ _ inch teddy bear ]字段的数据。

注:通配符搜索只能用于文本字段(串),非文本数据类型字段不能使用通配符搜索。

猜你喜欢

转载自blog.51cto.com/13767783/2168959