2011-01-21 117 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