-- 高级数据过滤 关键词:where子句 | not 和in 操作符
-- 组合where子句 (给出多个where子句。有两种使用方式:以and子句或or子句的方式使用)
-- and操作符(相当于给where子句添加了附加条件)
select prod_id,prod_price,prod_name
from products
where vend_id = 'dll01' and prod_price <=4;
-- 因为只有一个and子句,最多有两个过滤条件,可以增加多个过滤条件,每个条件间都要使用and关键字
-- or操作符(检索匹配任一条件的行,在dbms中,在第一个条件满足时,不管第二个条件是否满足,相应的行都被检索出来)
select prod_name,prod_price
from products
where vend_id = 'dll01' or vend_id = 'brs01';
-- 求值顺序(and和or两者结合可以进行复杂高级的过滤)(where子句中可以包含任意数目的and和or操作符)
select prod_name,prod_price
from products
where vend_id = 'dll01' or vend_id = 'brs01'
and prod_price >= 10;
我们会发现输出的结果并非达到我们的预期,原因就是sql在处理or操作符的时候,优先处理and操作符,导致操作符被错误的组合成价格在10美元以上的brs01以及任意价格的dll01,导致输出错误的结果。
解决方法是使用圆括号对操作符进行明确分组。
select prod_name,prod_price
from products
where (vend_id = 'dll01' or vend_id = 'brs01')
and prod_price >= 10;
-- in操作符(用来指定条件范围,范围中的每个条件都可以进行匹配)(由一组逗号分隔、括在圆括号中的合法值)
select prod_name,prod_price
from products
where vend_id in ('dll01','bres01')
order by prod_name;
-----------------------
select prod_name,prod_price
from products
where vend_id = 'dll01' or vend_id = 'brs01'
order by prod_name;
在这里发现使用in操作符和or操作符输出的结果大致相当(书中两个表结果完全相同,可能是dbms的不同导致的差异,也可能是表的外部连接的影响)。但是可以发现in操作符的优点大概如下:
1.in操作符的语法更清楚,更直观。
2.in在与(and/or)操作符混合使用的时候,求值顺序更容易管理。
3.in操作符一般比一组or操作符执行得更快。
4.in操作符最大的优点是可以包含其他select语句,能够更动态地简历where字句。
-- not操作符(特点:从不单独使用;用在过滤的条件前后都可以)(功能:where子句中用来否定其后条件的关键字)
select prod_name
from products
where not vend_id = 'dll01'
order by prod_name;
等同于
select prod_name
from products
where vend_id <> 'dll01'
order by prod_name;
在简单的where子句中not优势并不明显,但是在更加复杂的子句中,not非常有用。比如和in操作符联合使用,可以非常简单地找出与条件列表不匹配的行。
如对本文有疑问, 点击进行留言回复!!
集合类 ArrayList 和 LinkedList 直接用 Innodb(MySQL 5.0
MySQL Innodb 存储结构 和 存储Null值 用法详解
网友评论