2016-11-10 106 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