SQL (四)高级数据过滤(组合where子句建立高级搜索条件)

where子句的and,or操作符

需要更强的过滤控制,之前都是用的单一条件,即只用一个where子句,现在用多个where子句组合更多的条件。组合方式有两只在种:and子句的方式,或者or子句的方式

在这里插入图片描述
and, or就是逻辑操作符
在这里插入图片描述

and逻辑操作符

在这里插入图片描述

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

在这里插入图片描述
可以有更多条件

select prod_id, prod_price, prod_name
from products
where vend_id = 'DLL01' AND prod_price <=4 and prod_id='BNBG03';

在这里插入图片描述

or逻辑操作符

在这里插入图片描述
有的实现里,有短路性质,有的没有,比如mysql就没有
在这里插入图片描述

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

从这里的实际输出来看,并没有短路,第一个条件和第二个条件都执行了的
在这里插入图片描述

求值顺序:and 和 or相遇,用圆括号对操作符明确分组

主要是涉及到优先级,and的优先级比or高,所以要用括号,括号的优先级比and更高

select prod_name, prod_price, vend_id
from products
where vend_id = 'DLL01' OR vend_id = 'BRS01'
AND prod_price >= 10;

看来,最后一个and条件只作用于了vend_id = 'BRS01’条件。
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

select prod_name, prod_price, vend_id
from products
where (vend_id = 'DLL01' OR vend_id = 'BRS01')
AND prod_price >= 10;

在这里插入图片描述

在这里插入图片描述

IN 操作符:指定条件范围,和OR功能一样

在这里插入图片描述

select prod_name, prod_price, vend_id
from products
where vend_id in ('DLL01', 'BRS01')
ORDER BY prod_name;

在这里插入图片描述

其实in的功能和or一样,但是代码更短

select prod_name, prod_price, vend_id
from products
where vend_id ='DLL01' or vend_id = 'BRS01'
ORDER BY prod_name;

在这里插入图片描述

not操作符:复杂子句中非常有用

在这里插入图片描述

select prod_name, vend_id
from products
where not vend_id = 'DLL01'
ORDER BY prod_price;

在这里插入图片描述
和下面的两段代码功能一样

select prod_name, vend_id
from products
where vend_id != 'DLL01'
ORDER BY prod_price;
select prod_name, vend_id
from products
where vend_id <> 'DLL01'
ORDER BY prod_price;

在这里插入图片描述

总结

  • 注意用圆括号管理求值顺序
  • 用and,or操作符组合where子句
  • 用in和not操作符筛选条件
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值