2016-11-10 38 views
1

該CSV具有在格式的圖像的網址 -如何讀取存儲過程中的csv以使csv需要數據提取?

www.domain.com/table_id/x_y_height_width.jpg 

我們想在存儲過程中從這些URL中提取的table_id,X,Y,寬度和高度,然後使用在多個SQL查詢這些參數。

我們該怎麼做?

+0

您可以使用外部數據封裝器讀取CSV爲表。問題的其餘部分已在下面回答。 https://www.postgresql.org/docs/current/static/file-fdw.html – mlinth

回答

2

regexp_split_to_array and split_part functions

create or replace function split_url (
    _url text, out table_id int, out x int, out y int, out height int, out width int 
) as $$ 
    select 
     a[2]::int, 
     split_part(a[3], '_', 1)::int, 
     split_part(a[3], '_', 2)::int, 
     split_part(a[3], '_', 3)::int, 
     split_part(split_part(a[3], '_', 4), '.', 1)::int 
    from (values 
     (regexp_split_to_array(_url, '/')) 
    ) rsa(a); 
$$ language sql immutable; 

select * 
from split_url('www.domain.com/234/34_12_400_300.jpg'); 
table_id | x | y | height | width 
----------+----+----+--------+------- 
     234 | 34 | 12 | 400 | 300 

要使用該功能與其他表做lateral

with t (url) as (values 
    ('www.domain.com/234/34_12_400_300.jpg'), 
    ('www.examplo.com/984/12_90_250_360.jpg') 
) 
select * 
from 
    t 
    cross join lateral 
    split_url(url) 
; 
        url     | table_id | x | y | height | width 
---------------------------------------+----------+----+----+--------+------- 
www.domain.com/234/34_12_400_300.jpg |  234 | 34 | 12 | 400 | 300 
www.examplo.com/984/12_90_250_360.jpg |  984 | 12 | 90 | 250 | 360 
+0

這真的很有幫助!謝謝! – Tisha