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

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


1)使用where子句spa

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

select prod_name, prod_price from Products where prod_price = 3.49;排序

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


除了上述例子的相等条件判断,where子句还支持如下条件操做符:
clip_image001get

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

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

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


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

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 ]字段的数据。

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

相关文章
相关标签/搜索