7

我在 Postgres 中有一个数组搜索,至少匹配一个标签,如下所示:

SELECT * FROM users WHERE tags && ['fun'];

| id | tags      |
| 1  | [fun,day] | 
| 2  | [fun,sun] |

可以匹配前缀吗?就像是:

SELECT * FROM users WHERE tags LIKE 'f%';

| id | tags      |
| 1  | [fun,day] | 
| 2  | [fun,sun] |
| 3  | [far]     | 
| 4  | [fin]     |
4

2 回答 2

5

尝试这个

create table users (id serial primary key, tags text[]);

insert into users (tags)
values
  ('{"fun", "day"}'),
  ('{"fun", "sun"}'),
  ('{"test"}'),
  ('{"fin"}');

select *
from users
where exists (select * from unnest(tags) as arr where arr like 'f%')

SQL 提琴示例

于 2013-07-10T05:28:48.947 回答
3

这是一个工作示例,应该或多或少地为您提供所需的东西。请注意,我并不是说这种方法可以扩展......

create table users (
id      serial primary key,
tags    text[] not null
);

insert into users (tags) values
('{"aaaa","bbbb","cccc"}'::text[]),
('{"badc","dddd","eeee"}'::text[]),
('{"gggg","ffbb","attt"}'::text[]);

select *
from (select id,unnest(tags) arr from users) u
where u.arr like 'a%';

 id | arr  
----+------
  1 | aaaa
  3 | attt
于 2013-07-10T02:45:36.657 回答