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

And*_*rus 4 sql postgresql

产品名称包含由空格分隔的单词.第一个字是品牌等的第二个字.

如何从字符串中提取这些单词,eq如何实现如下查询:

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) );
Run Code Online (Sandbox Code Playgroud)

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

小智 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} )
Run Code Online (Sandbox Code Playgroud)