谓词是函数的一种,是需要满足特定条件的一种,该条件就是返回值为真值。
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);