2011-09-03 22 views
7

我在包含幾個數組列的PostgreSQL數據庫中構建了一系列視圖。該視圖的定義如下:在PostgreSQL中查找數組列中的字符串

create view articles_view as 
    (select articles.*, 
    array(select row(people.*)::people 
    from people 
    where articles.spubid=people.spubid and 
     people.stype='Author' and 
     bactive='t' 
    order by people.iorder) as authors, 
    array(select row(people.*)::people 
    from people 
    where articles.spubid=people.spubid and 
     people.stype='Editor' and 
     bactive='t' 
    order by people.iorder) as editors, 
    array(select row(people.*)::people 
    from people 
    where articles.spubid=people.spubid and 
     people.stype='Reviewer' and 
     bactive='t' 
    order by people.iorder) as reviewers, 
    array(select row(status.*)::status 
    from status 
    where articles.spubid=status.spubid and 
     bactive='t') as status 
    from articles 
    where articles.bactive='t'); 

從本質上講就是我想要做的是對「作者」列中的iLike的,以確定是否該陣列中是否存在特定的用戶ID。顯然,我不能在該數據類型上使用iLike,所以我需要找到另一種方法。

這裏是「作者的陣列中的數據的一個示例:

{ 」(2373,T,F,F,\「 2011-08-01 11:57:40.696496 \」, /Pubs/pubs_edit_article.php,\"2011-08-09 15:36:29.281833 \「,000128343,A00592,Author,1,Nicholas,K.,Kreidberg,\」\「,123456789,t,Admin,A ,A,A,0,\「\」)「,」(2374,t,f,f,\「2011-08-01 11:57:40.706617 \」,/ Pubs/pubs_edit_article.php,「2011 -08-09 15:36:29.285428 \「,000128343,A00592,作者,2,約翰,D.,Doe,\」\「,234567890,t,IT,A,A,A,0, 「)」,「(2381,t,f,f,」2011-08-09 14:45:14.870418 \「,000128343,\」2011-08-09 15:36:29.28854 \「,000128 343,A00592,作者,3,簡,E,DOE,\ 「\」,345678901,T,管理員,A,A,A ,, \ 「\」) 「」(2383,T,F,F,\ 「2011-08-09 15:35:11.845283 \」,567890123,\「2011-08-09 15:36:29.291388 \」,000128343,A00592,作者,4,Test,T,Testerton, 「,TestTesterton,f,N/A,A,A,A ,, \」\「)」}

我希望能夠做的是查詢視圖並找出字符串' 123456789'(即陣列中分配給Nicholas Kreidberg的用戶標識)存在於數組中。我不關心它分配給哪個用戶或它出現在數組中的位置,我只需要知道是否'123456789'出現在陣列中的任何位置。

一旦我知道如何編寫一個查詢來確定上述條件是否爲true,那麼我的應用程序將簡單地執行該查詢,並且如果返回行,它將知道傳遞給查詢的用戶ID是該出版物的作者並相應地進行。

在此先感謝您提供有關此主題的任何見解。

+4

有什麼理由不能使用正確的數據庫結構?即爲作者提供了一個單獨的表格,並且它是一個m:n關係,這是一個將文章映射到作者的表格。 – ThiefMaster

+3

@ThiefMaster數組由postgres提供,詢問如何在其中進行搜索是一個合理的問題。 –

+0

@Dana,它仍然是一種反模式(沒有規範化,沒有可能的索引,連接是一種痛苦,搜索是一種痛苦,而且它們超級慢)。 – Johan

回答

17

可能會這樣:

select ... 
    from ... 
where ... 
     and array_to_string(authors, ', ') like '%123456789%';` 

做的伎倆?

否則,有unnest功能...

的 「Array Functions and Operators」 一章有更多細節。