LIKE - Amazon Redshift
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

LIKE

LIKE 运算符将字符串表达式(如列名称)与使用通配符 %(百分比)和 _(下划线)的模式进行比较。LIKE 模式匹配始终涵盖整个字符串。若要匹配字符串中任意位置的序列,模式必须以百分比符号开始和结尾。

LIKE 区分大小写;ILIKE 不区分大小写。

语法

expression [ NOT ] LIKE | ILIKE pattern [ ESCAPE 'escape_char' ]

参数

expression

有效的 UTF-8 字符表达式(如列名称)。

LIKE | ILIKE

LIKE 执行区分大小写的模式匹配。ILIKE 对单字节 UTF-8 (ASCII) 字符执行不区分大小写的模式匹配。要为多字节字符执行不区分大小写的模式匹配,请将 expression 上的 LOWER 函数和带有 LIKE 函数的 pattern 一起使用。

与比较谓词(例如 = 和 <>)相反,LIKE 和 ILIKE 谓词并不会隐式忽略尾随空格。要忽略尾随空格,请使用 RTRIM 或者将 CHAR 列显式强制转换为 VARCHAR。

~~ 运算符等同于 LIKE,而 ~~* 等同于 ILIKE。此外,!~~!~~* 运算符等同于 NOT LIKE 和 NOT ILIKE。

pattern

具有要匹配的模式的有效的 UTF-8 字符表达式。

escape_char

将对模式中的元字符进行转义的字符表达式。默认为两个反斜杠 ('\\')。

如果 pattern 不包含元字符,则模式仅表示字符串本身;在此情况下,LIKE 的行为与等于运算符相同。

其中一个字符表达式可以是 CHAR 或 VARCHAR 数据类型。如果它们不同,Amazon Redshift 会将 pattern 转换为 expression 的数据类型。

LIKE 支持下列模式匹配元字符:

操作符 描述
% 匹配任意序列的零个或多个字符。
_ 匹配任何单个字符。

示例

下表显示使用 LIKE 的模式匹配的示例:

表达式 返回值
'abc' LIKE 'abc' True
'abc' LIKE 'a%' True
'abc' LIKE '_B_' False
'abc' ILIKE '_B_' True
'abc' LIKE 'c%' False

以下示例查找名称以“E”开头的所有城市:

select distinct city from users where city like 'E%' order by city; city --------------- East Hartford East Lansing East Rutherford East St. Louis Easthampton Easton Eatontown Eau Claire ...

以下示例查找姓中包含“ten”的用户:

select distinct lastname from users where lastname like '%ten%' order by lastname; lastname ------------- Christensen Wooten ...

以下示例演示如何匹配多个模式。

select distinct lastname from tickit.users where lastname like 'Chris%' or lastname like '%Wooten' order by lastname; lastname ------------- Christensen Christian Wooten ...

以下示例查找第三和第四个字符为“ea”的城市。此命令使用 ILIKE 来演示不区分大小写的匹配:

select distinct city from users where city ilike '__EA%' order by city; city ------------- Brea Clearwater Great Falls Ocean City Olean Wheaton (6 rows)

以下示例使用默认转义字符串(\\)搜索包含“start_”(文本 start 后跟下划线 _)的字符串:

select tablename, "column" from pg_table_def where "column" like '%start\\_%' limit 5; tablename | column -------------------+--------------- stl_s3client | start_time stl_tr_conflict | xact_start_ts stl_undone | undo_start_ts stl_unload_log | start_time stl_vacuum_detail | start_row (5 rows)

以下示例指定“^”作为转义字符,然后使用该转义字符搜索包含“start_”(文本 start 后跟下划线 _)的字符串:

select tablename, "column" from pg_table_def where "column" like '%start^_%' escape '^' limit 5; tablename | column -------------------+--------------- stl_s3client | start_time stl_tr_conflict | xact_start_ts stl_undone | undo_start_ts stl_unload_log | start_time stl_vacuum_detail | start_row (5 rows)

以下示例使用 ~~* 运算符对以“Ag”开头的城市进行不区分大小写(ILIKE)的搜索。

select distinct city from users where city ~~* 'Ag%' order by city; city ------------ Agat Agawam Agoura Hills Aguadilla