SQL之通配符过滤

操作符like

通配符本是实际是SQL的where子句中有特殊含义的字符,SQL支持几种通配符。为了在搜索子句里使用通配符,必须使用like操作符。

1.%通配符

%表示出现任意次数的任意字符

找出fish开头的产品。

select prod_id,prod_name 
from Products
where prod_name like "Fish%";

找出中间有fish的产品

select prod_id,prod_name 
from Products
where prod_name like "%Fish%";

2._通配符

下划线用途与%一样,但是只匹配单个字符

找出类似“Fish 12”或者“Fish 21”,只能是类似的格式

select prod_id,prod_name 
from Products
where prod_name like "Fish __";

如果是%通配符,就能匹配到类似“Fish 8”

select prod_id,prod_name 
from Products
where prod_name like "Fish %";

3.[]通配符

方括号用来指定一个字符集,它必须匹配指定位置(通配符的位置)的一个字符

例如找出以名字以J或者M起头的联系人

select cust_contact
from customers  
where cust_contact like "[JM]%"
order by cust_contact;

此外可以用前缀字符^来否定,找出除J或者M起头之外的联系人。

select cust_contact
from customers  
where cust_contact like "[^JM]%"
order by cust_contact;

当然使用not操作符也可以

select cust_contact
from customers  
where not cust_contact like "[JM]%"
order by cust_contact;

4。使用技巧

1.在具体不同的sql中通配符细节上会有所不同。

2.不要过度使用通配符,如果能不用就尽量不用。

3.不要把通配符用在搜索模式的开始处。

猜你喜欢

转载自www.cnblogs.com/haoqirui/p/10367057.html