2014-06-29 20 views
-1

我的子查詢不會產生正面影響。請幫忙。列元素是字符串,用逗號分隔;Postgresql子查詢語句中的字符串文本

select id, title, elements, (
    select string_agg(distinct street, ',') 
    from locations 
    where elementnames in (replace(quote_nullable(elements),',',''',''')) 
) as buildings 
from events ; 


    id  | title |  elements  | buildings 
-----------+-------+---------------------+---------- 
124003 | alpha | NYCID005   | 
000111 | beta | NYCID222   | 
20| gamma | NYCID201,NYCID193 | 
102036 | sigma | NYCID202,NYCID191 | 
(4 rows) 
+1

請不要在一列中存儲逗號分隔值。你的問題是不好的設計的直接結果 –

+0

我可以改變架構,請給我一個例子如何改變它。 – elektromonter

回答

0

我找到了一些解決方案。

select id,title,elements, 
    (select string_agg(distinct street, ',') from locations 
    where (string_to_array(elementnames,',') <@ (string_to_array(elements,',')))) as buildings 
from events; 

    id  | title |  elements  |   buildings  | 
-----------+-------+---------------------+---------------------------+ 
124003 | alpha  | NYCID005   | Ford,Harrison    | 
000111 | beta  | NYCID222   | Stallone,Malkovitch  | 
200124 | gamma  | NYCID201,NYCID193 | Gates Street,Ostin  |