PostgreSQL,将数组嵌套到值中

时间:2019-03-01 13:05:35

标签: sql arrays postgresql unnest

假设我输入了文字:

周六购买,XXX交付,地址YYY,付款方式ZZZ

请向我们报价价格和库存状况

К52-1Б - 68мкф/50в
К52-1 - 100мкф/63в

如何修改此查询,所以不需要手动拆分行?

with long_string (ls) as (values
    ('Buying on Saturday, delivery by XXX, address YYY, payment method ZZZ'),
    ('Please quote us on prices and stock availability'),
    ('К52-1Б - 68мкф/50в'),
    ('К52-1 - 100мкф/63в')
)
select products.*, matches, similarity
from products
cross join long_string
cross join lateral
(select
    (name % ls)::int as matches,
    similarity(name, ls) as similarity
) m
where matches > 0 and similarity > 0.7
order by matches desc, similarity desc;

我尝试过

with long_string (ls) as (
    values
        unnest(string_to_array('Buying on Saturday, delivery by XXX, address YYY, payment method ZZZ 
        Please quote us on prices and stock availability
        К52-1Б - 68мкф/50в
        К52-1 - 100мкф/63в', '\n'))
    )
select products.*, matches, similarity
....

但是有一个错误ERROR: syntax error at or near "unnest"

2 个答案:

答案 0 :(得分:3)

如果这只是解析字符串,那么:

with long_string (ls) as (
    select unnest(string_to_array(str, E'\n'))
    from (values ('Buying on Saturday, delivery by XXX, address YYY, payment method ZZZ 
Please quote us on prices and stock availability
К52-1Б - 68мкф/50в
К52-1 - 100мкф/63в')
         ) v(str)
    )
select ls
from long_string;

Here是db <>小提琴。

答案 1 :(得分:1)

或者您可以这样做:

with long_string (ls) as (
    select
         trim(regexp_split_to_table('Buying on Saturday, delivery by XXX, address YYY, payment method ZZZ
        Please quote us on prices and stock availability
        К52-1Б - 68мкф/50в
        К52-1 - 100мкф/63в', '\n'))
    )
select *
from long_string