SQL学习笔记——谓词(like,between,is null,is not null,in ,not in,exists,not exists)

谓词是函数的一种,是需要满足特定条件的一种,该条件就是返回值为真值。

1、like谓词,字符串的部分一致查询

在查询时可以使用符号“%”和“_”,% 是代表“0 字符以上的任意字符串”的特殊符号,“_”代表了“任意1 个字符”。

select *
from<表名>
where<列名> like 'ddd%';
--从这一列中,查询出前面三个字符时ddd的字符串,不管字符串的后面的部分是什么

select *
from<表名>
where<列名> like '%ddd';
--从这一列中,查询以ddd开头的字符串

select *
from<表名>
where<列名> like '%ddd%';
--从这一列中,查询出包含ddd的字符串

select *
from<表名>
where<列名> like 'ddd_';
--从这一列中,查询出以ddd开头,且ddd后面只有一个任意字符的字符串,

2、between谓词,范围查询

使用between进行范围查找时,会包含between所设置的临界值。

select product_name, sale_price
from product
where sale_price between 100 and 1000;

3、is null和is not null,判断是否为null

 为了选取出某些值为null的列的数据,不能使用“=”,而只能使用特定的谓词is null

select product_name, purchase_price
from product
where purchase_price is null;
--选取出purchase_price 是null的商品

select product_name, purchase_price
from product
where purchase_price is not null;
--选取出purchase_price 不是null的商品

4、in和not in谓词

使用in和not in时是无法选取出null数据的

select product_name, purchase_price
from product
where purchase_price in (320, 500, 5000);
--选取出purchase_price 为320 、500 、5000 的商品

select product_name, purchase_price
from product
where purchase_price in (320, 500, 5000);
--选取出purchase_price 不是320 、500 、5000 的商品

5、使用子查询作为in谓词的参数

in和not in具有其他谓词所没有的用法,那就是可以使用子查询作为其参数

select product_name, sale_price
from A
where product_id in (select product_id
                     from B
                     where shop_id = '000C');
--从表B中选出shop_id(表B中的字段) 为 '000C'的记录,再从表A中选出product_id(表A中的字段)存在于表B查询(子查询)结果中的记录。

select product_name, sale_price
from A
where product_id not in (select product_id
                     from B
                     where shop_id = '000C');
--从表B中选出shop_id(表B中的字段) 为 '000C'的记录,再从表A中选出product_id(表A中的字段)不存在于表B查询(子查询)结果中的记录。

6、exists谓词,判断是否存在满足某种条件的记录,如果存在这样的记录就返回真(true),如果不存在就返回假(false)。

select product_name, sale_price
from product as p1
where exists (select *
              from B as p2 
              where p2.shop_id = '000C'
              and p2.product_id = p1.product_id);

select product_name, sale_price
from product as p1
where not exists (select *
              from B as p2 
              where p2.shop_id = '000C'
              and p2.product_id = p1.product_id);

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值