2013-07-10 81 views
5

我在Postgres的帽子陣列搜索至少一個標籤,因爲這符合: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

試試這個

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 FIDDLE EXAMPLE

+0

存在條款是不正確 - 查看結果。它缺少對外部查詢關聯行的引用。嘗試添加AND'id = u.id'(是「u」是外部表的別名)。小提琴更新:http://sqlfiddle.com/#!12/a6940/10/0 – bma

+0

我沒有太多的PostgreSQL expirience(主要是在SQL服務器),但我敢肯定你錯了,而且BTW我的查詢在sqlfiddle中返回正確的結果。 Exists已經在處理當前行標記,所以你的id = u.id. SQLFIDDLE目前處於關閉狀態,所以稍後我會檢查它。 –

+1

基本上我的查詢可以改寫爲 'select * from users as u exists where(select * from unnest(u.tags)as arr where arr like'f%')' –

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