8

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

如何从字符串中提取这些单词,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) );

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

4

3 回答 3

13

您可以尝试使用功能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} )
于 2013-07-15T11:16:07.987 回答
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})
于 2013-07-15T11:37:52.637 回答
0

您正在寻找的可能split_part是 PostgreSQL 中的字符串函数。请参阅http://www.postgresql.org/docs/9.1/static/functions-string.html

于 2013-07-15T11:05:07.993 回答