【问题标题】:how to extract specific word from string in Postgres如何从Postgres中的字符串中提取特定单词
【发布时间】:2013-07-15 11:00:09
【问题描述】:

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

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

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() 或其他函数来提高速度?

【问题讨论】:

  • “只是某人”想说的是:您的数据库模型错误。阅读规范化

标签: sql postgresql


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您正在寻找的可能是split_part,它在 PostgreSQL 中作为字符串函数提供。见http://www.postgresql.org/docs/9.1/static/functions-string.html

    【讨论】:

      【解决方案3】:
      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})
      

      【讨论】:

        猜你喜欢
        • 2020-06-17
        • 1970-01-01
        • 2021-07-28
        • 1970-01-01
        • 2023-02-13
        • 2023-03-24
        • 1970-01-01
        • 1970-01-01
        • 2022-11-21
        相关资源
        最近更新 更多