在本教程中,您将学习如何使用oracle like
运算符来测试列中的值是否与指定的模式匹配。
有时候,想根据指定的模式来查询数据。 例如,您可能希望查找姓氏以st
开头或姓氏以er
结尾的联系人。在这种情况下,可使用oracle like
运算符。
oracle like
运算符的语法如下所示:
expresion [not] like pattern [ escape escape_characters ]
在上面的语法中,
pattern
)进行测试。escape_character
是出现在通配符前面的字符,用于指定通配符不应被解释为通配符而是常规字符。escape_character
(如果指定)必须是一个字符,并且没有默认值。
如果表达式匹配模式,like
运算符返回true
。 否则,它返回false
。
not
运算符(如果指定)否定like
运算符的结果。
下面举一些使用oracle like
运算符的例子来看看它是如何工作的。
这里将使用示例数据库中的contacts
表进行演示:
以下示例使用%
通配符查找姓氏以st
开头的联系人的电话号码:
select
first_name,
last_name,
phone
from
contacts
where
last_name like 'st%'
order by
last_name;
执行上面查询语句,得到以下结果 -
在这个例子中,使用了这个模式:
'st%'
like
运算符匹配任何以“st”
开头的字符串,后跟任意数量的字符,例如stokes
,stein
或steele
等。
要查找姓氏以字符串“er”
结尾的联系人的电话号码,请使用以下语句:
select
first_name,
last_name,
phone
from
contacts
where
last_name like '%er'
order by
last_name;
执行上面查询语句,得到以下结果 -
匹配的模式 -
%er
匹配任何以“er”
字符串结尾的字符串。
要执行不区分大小写的匹配,可以使用lower()
或upper()
函数,如下所示:
upper( last_name ) like 'st%'
lower(last_name like 'st%'
例如,以下语句查找名字以ch
开头的联系人的电子邮件:
select
first_name,
last_name,
email
from
contacts
where
upper( first_name ) like 'ch%'
order by
first_name;
执行上面查询语句,得到以下结果 -
以下示例使用not like
运算符来查找电话号码不以“+1”
开头的联系人:
select
first_name, last_name, phone
from
contacts
where
phone not like '+1%'
order by
first_name;
执行上面查询语句,得到以下结果 -
以下示例查找名字具有以下模式“je_i”
的联系人的电话号码和电子邮件:
select
first_name,
last_name,
email,
phone
from
contacts
where
first_name like 'je_i'
order by
first_name;
执行上面查询语句,得到以下结果 -
模式'je_i'
匹配任何以'je'
开头的字符串,然后是一个字符,最后是'i'
,例如jeri
或jeni
,但不是jenni
。
可以在模式中混合通配符。例如,以下语句查找名字以j
开头,后跟两个字符,然后是任意数量字符的联系人。换句话说,它将匹配以je
开头并且至少有4
个字符的任何姓氏(first_name
):
select
first_name,
last_name,
email,
phone
from
contacts
where
first_name like 'je_%';
执行上面查询语句,得到以下结果 -
escape
子句允许查找包含一个或多个通配符的字符串。
例如,表可能包含具有百分比字符的数据,例如折扣值,折旧率。要搜索字符串25%
,可以使用escape
子句,如下所示:
like '%25!%%' escape '!'
如果不使用escape
子句,则oracle将返回字符串为25
的任何行。
以下语句创建折扣(discounts
)表并插入一些用于测试的示例数据:
create table discounts
(
product_id number,
discount_message varchar2( 255 ) not null,
primary key( product_id )
);
-- 插入3条数据
insert into discounts(product_id, discount_message)
values(1, 'buy 1 and get 25% off on 2nd ');
insert into discounts(product_id, discount_message)
values(2, 'buy 2 and get 50% off on 3rd ');
insert into discounts(product_id, discount_message)
values(3, 'buy 3 get 1 free');
如果不熟悉此脚本中使用的语句,则可以在随后的教程中学习它们。以下语句检索折扣25%
的产品:
select
product_id, discount_message
from
discounts
where
discount_message like '%25!%%' escape '!';
执行上面查询语句,得到以下结果 -