简体   繁体   中英

how to extract specific word from string in Postgres

Product name contains words deliminated by space. First word is size second in brand etc.

How to extract those words from string, eq how to implement query like:

select
  id,       
  getwordnum( prodname,1 ) as size,
  getwordnum( prodname,2 ) as brand
  from products
where ({0} is null or getwordnum( prodname,1 )={0} ) and
    ({1} is null or getwordnum( prodname,2 )={1} )


create table product ( id char(20) primary key, prodname char(100) );

How to create getwordnum() function in Postgres or should some substring() or other function used directly in this query to improve speed ?

You could try to use function split_part

select
  id,       
  split_part( prodname, ' ' , 1 ) as size,
  split_part( prodname, ' ', 2 ) as brand
  from products
where ({0} is null or split_part( prodname, ' ' , 1 )= {0} ) and
    ({1} is null or split_part( prodname, ' ', 2 )= {1} )

What you're looking for is probably split_part which is available as a String function in PostgreSQL. See http://www.postgresql.org/docs/9.1/static/functions-string.html .

select
    id,       
    prodname[1] as size,
    prodname[2] as brand
from (
    select
        id,
        regexp_split_to_array(prodname, ' ') as prodname
    from products
) s
where
    ({0} is null or prodname[1] = {0})
    and
    ({1} is null or prodname[2] = {1})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM