谓词(predicate),这里和英语语法中的谓词差不多,之前的介绍中也提到了一些谓词,比如 > < = >= <= <>这些符号,翻译成英文,bigger than/less than等等,这些就是比较谓词,谓词还是函数的一部分,不同的函数输出结果可能各式各样,但是谓词只输出真值TRUE/FALSE/UNKNOWN,本文介绍的谓词有LIKE/BETWEEN/IS NULL/IS NOT NULL/IN/EXISTS,这些谓词都是跟着WHERE的判断。
1.谓词
1.1 模糊匹配-LIKE
LIKE还是很好用的,和正则表达式有点像,适用于模糊搜索,需要搭配"%"和"_"符号进行使用,"%"表示零到无限字符,可以左右中间三种形式的模糊匹配,"_"符号表示一个字符。
select * from sale where product_name like "牛%"; select * from sale where product_name like '%裤'; select * from sale where product_name like '%仔%'; select * from sale where product_name like '_仔_';
1.2 范围查询-BETWEEN
select * from sale where sale_price between 5 and 100;
1.3 判断是否为空-IS NULL/IS NOT NULL
select * from math where m is not null; select * from math where m is NULL;
1.4 OR的简单用户-IN
以下两个语句运行的结果一致,对于通一元素有多个可能性,需要用OR进行连接,每多一个可能性就多一个OR,语句非常的繁琐,用IN可以代替多个可能性。
select * from sale where product_name='雪碧' or product_name='可乐' or product_name='白酒'; select * from sale where product_name in ('雪碧','可乐','白酒'); select * from sale where product_name NOT in ('雪碧','可乐','白酒');
IN的元素可以是子查询的结果。
select product_name,purchase_price from sale where product_name in (select product_name from supply where locate='南京'); select product_name,purchase_price from sale where product_name not in (select product_name from supply where locate='南京');
1.5 EXISTS
EXISTS的用法较之前的谓词都不一样,语法理解起来比较困难,EXISTS是一种SQL中级水平的工具,其实他的大都数的应用都可以用IN和NOT IN替代,但是如果能够很好的理解并熟练的使用EXISTS,就能体会到它的便利性。
select * from sale as P1 where exists (select * FROM supply as P2 where P1.product_name = P2.product_name and P2.locate = '西安');
我理解的是EXISTS语句和之前关联子查询的循环判断一样,括号内的是判断语句,输出TRUE和FALSE,如果判断TRUE则输出外部的SELECT查询内容。
2.CASE WHEN......THEN......ELSE.....END AS......表达式
暂时用的不多,就当先练习练习吧,因为需求并不是很多,用不到。
select sale_price,CASE WHEN product_type='衣服' THEN concat('A: ',product_type) WHEN product_type='酒水' THEN concat('B: ',product_type) WHEN product_type='办公用品' THEN concat('C: ',product_type) WHEN product_type='食品' THEN concat('D: ',product_type) ELSE NULL END AS ab_product_type from sale;
select sum(CASE WHEN product_type='食品' THEN sale_price else null end) as food_price, sum(CASE WHEN product_type='酒水' THEN sale_price else null end) as drink_pirce, sum(CASE WHEN product_type='衣服' THEN sale_price else null end) as cloth_price from sale;
select count(CASE WHEN sale_price <= 10 THEN product_id else null end) as low_price, count(CASE WHEN sale_price >10 and sale_price <= 100 THEN product_id else null END) as middle_price, count(CASE WHEN sale_price > 100 THEN product_id else null END) as high_price from sale;