2011-01-21 66 views
2

我有2个表:涉及PostgreSQL的查询整数[]

CREATE TABLE article ( 
    id serial NOT NULL, 
    title text, 
    tags integer[] -- array of tag id's from TAG table 
) 

CREATE TABLE tag (
    id serial NOT NULL, 
    description character varying(250) NOT NULL 
) 

...并需要根据文章的标题,以从在文章的“标签整数[]”举行标记表。

所以想是这样

SELECT * 
    FROM tag 
WHERE tag.id IN ((select article.tags::int4 
         from article 
        where article.title = 'some title')); 

...这使我

ERROR: cannot cast type integer[] to integer
LINE 1: ...FROM tag WHERE tag.id IN ( (select article.tags::int4 from ...

我在这两个开发和生产环境与PostgreSQL 8.3版本卡住。

回答

4

使用阵列重叠算子&&

SELECT * 
    FROM tag 
    WHERE ARRAY[id] && ANY (SELECT tags FROM article WHERE title = '...'); 

使用contrib/intarray你甚至可以很好地指出这种事情。

4

看看节“8.14.5. Searching in Arrays”,但在这节结束时考虑的提示:

Tip: Arrays are not sets; searching for specific array elements can be a sign of database misdesign. Consider using a separate table with a row for each item that would be an array element. This will be easier to search, and is likely to scale better for a large number of elements.

2

你没有提到你的Postgres版本,所以我假设你使用的是上TO-最新版本(8.4,9.0)

这应该有帮助:

 
SELECT * 
    FROM tag 
WHERE tag.id IN (select unnest(tags) 
        from article 
        where title = 'some title'); 

但你真的应该考虑改变你的表的设计。

编辑

对于8.3 UNNEST()可以很容易地添加功能,请参阅本wiki页面:
http://wiki.postgresql.org/wiki/Array_Unnest

+0

...无赖,我是8.3,既dev和prod :-( – vector 2011-01-21 17:34:35

+0

...你打赌我,它是,我发现:-) – vector 2011-01-21 17:54:38