2013-07-10 2 views
5

I 포스트 그레스 모자에 배열 검색이 적어도 하나 개의 태그와 일치 있습니다 : 접두사에 일치 할 수포스트 그레스 배열 접두사 일치

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

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

를? 다음과 같음 :

답변

4

는 EXISTS 절이

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"는 외부 테이블의 별칭입니다). Fiddle updated : http://sqlfiddle.com/#!12/a6940/10/0 – bma

+0

PostgreSQL에서 대부분 expirience가 없습니다 (대부분 SQL 서버에 있음),하지만 당신이 틀렸다고 확신하고 BTW 내 쿼리는 sqlfiddle에서 올바른 결과를 반환합니다. Exists가 현재 행 태그에서 이미 작동하고 있으므로 id = u.id입니다. SQLFIDDLE은 잠시 중단되었으므로 나중에 확인하겠습니다. –

+1

기본적으로 내 쿼리는 으로 다시 쓰여질 수 있습니다. 'select * from users as where where (존재하지 않는 (u.tags) 중에서 arr을'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