謂詞是函數的一種,是需要滿足特定條件的一種,該條件就是返回值爲真值。
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);