如何从Postgres中的字符串中提取特定单词

时间:2013-07-15 11:00:10

标签: sql postgresql

产品名称包含按空格划分的字词。 第一个字是品牌等的第二个字。

如何从字符串中提取这些单词,e.q如何实现查询:

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) );

如何在Postgres中创建getwordnum()函数或者是否应该在此查询中直接使用某些substring()或其他函数来提高速度?

3 个答案:

答案 0 :(得分:7)

您可以尝试使用 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} )

答案 1 :(得分:0)

你正在寻找的东西可能是split_part,它可以作为PostgreSQL中的String函数使用。请参阅http://www.postgresql.org/docs/9.1/static/functions-string.html

答案 2 :(得分:0)

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})