逻辑运算符
使用逻辑运算符可以将多个查询条件进行组合
NOT 运算符
指定“不是 ~ 这样否定条件时,需要使用<>运算符,除此之外,还存在一个表示否定,并且使用范围更广的运算符 NOT”
注意:NOT不能单独使用,必须和其他条件组合起来使用。
select product_name,product_type,sale_price
from product
where sale_price >= 1000;
加入NOT 后
select product _name,product_type,sale_price
from product
where not sale_price >=1000;
所以案例中的 sale_price >= 与 sale_price<1000是等价的;
AND 运算符和OR运算符
在where子句中使用and 运算符和 or 运算符,可以对多个查询条件进行组合。
AND 运算符在其两侧的查询条件都成立时整个查询条件才成立。其意思相当于“并且”
OR 运算符在其两侧的查询条件有一个成立时整个查询条件都成立,其意思相当与“或者”。
SELECT product_name, purchase_price
FROM Product
WHERE product_type = '厨房用具'
AND sale_price >= 3000;
SELECT product_name, purchase_price
FROM Product
WHERE product_type = '厨房用具'
OR sale_price >= 3000;
通过括号强化处理
案例:查询商品名称为“办公用品” 并且 “登记日期是2009年9月1日或者2009年9月20日”
通过数据库可以看到,满足条件的只有“打孔器"这个物品,把上述条件写入where子句中,得到的select语句似乎满足需求了:
select product_name,product_type,regist_date
from product
where product_type ="办公用品"
and regist_date = '2009-09-01'
or regist_date ='2009-09-20'
执行结果:
product_name | product_type | regist_date
T恤衫 | 衣服 | 2009-09-20
打孔器 | 办公用品 | 2009-09-11
菜刀 | 厨房用具 | 2009-09-20
叉子 | 厨房用具 | 2009-09-20
不想要的T恤衫、菜刀、叉子也被查出来了,这是什么原因造成呢?
这是因为AND 运算符的优先级高于OR运算符优先级造成的
查询语句会被解释为:
(product_type = '办公用品' AND regist_date = '2009-09-11')
OR
(regist_date = '2009-09-20')
这和想要的查询条件不符,想要优先执行OR运算符,可用()括号将or运算符及其两侧的查询条件括起来。
select product_name,product_type,regist_date
from product
where product_type ="办公用品"
and( regist_date = '2009-09-01' or regist_date ='2009-09-20')
那么这样的话,就可以查到我们想要的结果了。
注意:查询 NULL 时不能使用比较运算符(= 或者 <>),需要使用 IS NULL 运算符或者 IS NOT NULL 运算符。
练习:
select product_name, regist_date from
Product where regist_date > '2009-04-28'
无返回结果:
① select product_name,sale_price,purchase_price
from Product
where (sale_price - purchase_price)>=500;
②select product_name,sale_price,purchase_price
from Product
where not (sale_price - purchase_price)<500;
③select product_name,sale_price,purchase_price
from Product
where sale_price >= purchase_price + 500
④select product_name,sale_price,purchase_price
from Product
where sale_price-500 >= purchase_price
select
product_name,
product_type,
sale_price*0.9-purchase_price AS profit
from Product
where sale_price*0.9 -purchase_price >100
and (product_type= '办公用品' or product_type = '厨房用具');