ITPub博客

首页 > 数据库 > PostgreSQL > PostgreSQL DBA(124) - Develop(Putting multiple LIKE patterns into an array)

PostgreSQL DBA(124) - Develop(Putting multiple LIKE patterns into an array)

原创 PostgreSQL 作者:husthxd 时间:2019-11-07 15:20:06 0 删除 编辑

本节简单介绍了PostgreSQL中的Putting multiple LIKE patterns into an array特性。

LIKE用于模糊查询,如select from tablename where column like ‘%value%’;如需要多个模糊匹配则需要使用多个like子句,如select from tablename where column like ‘%value1%’ or column like ‘%value2%’ or column like ‘%value3%’或者select * from tablename where column like ‘%value1%’ and column like ‘%value2%’ and column like ‘%value3%’。PG提供了ANY/ALL结合ARRAY来简化SQL:

select from tablename where column like ‘%value1%’ or column like ‘%value2%’ or column like ‘%value3%’
->
select from tablename where column like ANY(ARRAY[‘%value1%’,’%value2%’,’%value3%’])

select from tablename where column like ‘%value1%’ and column like ‘%value2%’ and column like ‘%value3%’
->
select from tablename where column like ALL(ARRAY[‘%value1%’,’%value2%’,’%value3%’])

测试脚本

[local]:5432 pg12@testdb=# create table t_like (id int,c1 varchar(20));
CREATE TABLE
Time: 160.410 ms
[local]:5432 pg12@testdb=# 
[local]:5432 pg12@testdb=# insert into t_like(id,c1) values(1,'asdfafetestsdfasdf');
INSERT 0 1
Time: 14.815 ms
[local]:5432 pg12@testdb=# insert into t_like(id,c1) values(2,'asdfafe测试sdfasdf');
INSERT 0 1
Time: 1.423 ms
[local]:5432 pg12@testdb=# insert into t_like(id,c1) values(3,'astestfe测试sdfasdf');
INSERT 0 1
Time: 1.486 ms
[local]:5432 pg12@testdb=# select * from t_like where c1 like ANY(ARRAY['%test%','%测试%']);
 id |         c1          
----+---------------------
  1 | asdfafetestsdfasdf
  2 | asdfafe测试sdfasdf
  3 | astestfe测试sdfasdf
(3 rows)
Time: 48.319 ms
[local]:5432 pg12@testdb=# select * from t_like where c1 like ALL(ARRAY['%test%','%测试%']);
 id |         c1          
----+---------------------
  3 | astestfe测试sdfasdf
(1 row)
Time: 2.463 ms
[local]:5432 pg12@testdb=#

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/6906/viewspace-2663070/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论