[英]how to extract specific word from string in Postgres
产品名称包含由空格分隔的单词。 第一个字是品牌等的第二个字。
如何从字符串中提取这些单词,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()或其他函数来提高速度?
您可以尝试使用函数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} )
您正在寻找的可能是split_part
,它可以作为PostgreSQL中的String函数使用。 见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})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.