【问题标题】:Extracting specific values with Postgresql使用 Postgresql 提取特定值
【发布时间】:2015-12-30 12:06:20
【问题描述】:

我有一张这样的桌子:

Table

<!DOCTYPE html>
<html>
<body>

<table border="1" style="width:100%">
  <tr>
    <td>email</td>
    <td>data</td>		
  </tr>
  <tr>
    <td>creator_a@creator.com</td>
    <td>"vimeo_profile"=>"", "twitter_profile"=>"", "youtube_profile"=>"", "creator_category"=>"production_company", "facebook_profile"=>"", "linkedin_profile"=>"", "personal_website"=>"", "instagram_profile"=>"", "content_expertise_categories"=>"4,5,8"</td>		
  </tr>
  <tr>
    <td>creator_b@creator.com</td>
    <td>"twitter_profile"=>"", "creator_category"=>"association", "facebook_profile"=>"", "linkedin_profile"=>"", "personal_website"=>"", "content_expertise_type"=>"image", "content_expertise_categories"=>"4, 6"</td>		
  </tr>
</table>

</body>
</html>

我想使用 PostgreSQL 查询这个,所以我只得到关于 content_expertise_categories 的值:

*重要的是要提到值的数量会有所不同。该表有更多条目,因此我正在寻找一种解决方案来帮助我提取值,无论是要提取 2 个值还是 15 个值。

Result

<!DOCTYPE html>
<html>
<body>

<table border="1" style="width:100%">
  <tr>
    <td>email</td>
    <td>data</td>		
  </tr>
  <tr>
    <td>creator_a@creator.com</td>
    <td>4,5,8</td>		
  </tr>
  <tr>
    <td>creator_b@creator.com</td>
    <td>4,6</td>		
  </tr>
</table>

</body>
</html>

我尝试了substring,但无法正常工作。

非常感谢您的帮助,谢谢!

【问题讨论】:

  • 编辑您的问题并在问题中包含数据和所需结果。 Stack Exchange 上的问题不应只是指向其他网站的链接。
  • select (string_to_array(data,'"content_expertise_categories"=&gt;'))[2];
  • 感谢 Vao 的快速回复;您能否在选择字段中包括我尝试选择“电子邮件”和“数据”以及“发件人”(表名是“用户”)?非常感谢!
  • select (string_to_array(data,'"content_expertise_categories"=&gt;'))[2] as data, email from users; ?..
  • 感谢 Vao。我正在使用 Navicat 9.1.2 并收到一条错误消息:“错误:函数 string_to_array(hstore, unknown) 不存在 LINE 2: select (string_to_array(data,'"content_expertise_categories"... ^ 提示:没有函数匹配给定名称和参数类型。您可能需要添加显式类型转换。"

标签: string postgresql substring extract


【解决方案1】:
SELECT 
  email,
  (string_to_array(
    data::text,'"content_expertise_categories"=>'::text
    )
  )[2] as data 
FROM users
;

更新:

在您的示例中,所有字符串最后都列出了“content_expertise_categories”,这允许您认为您可以将字符串拆分为两部分。如果您之后碰巧有更多的 php 数组定义值,您将需要在 ',"' 上进行额外拆分,并在这次参与 [1]...

content_expertise_categories 函数中使用它之前,请先将"data" 转换为::text,因为它需要文本类型,而您的列似乎不是这样。

我相信这个查询会更优雅:

select 
  email,
  data->'content_expertise_categories' as data
from h
;

但是当我发布第一个查询时,我不知道您使用的是 hstore

【讨论】:

  • 不推荐“仅代码” 答案。他们没有解释为什么您的代码是正确的以及为什么 OP 的代码(如果有的话)是错误的。即使代码对您或精通所使用的编程语言和/或 API 的人来说是直观的,最好的做法是答案包括解释,这样即使是刚接触编程的人也可以学习如何解决问题,而不仅仅是什么代码有效,但更重要的是,为什么该代码有效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-10
  • 2023-04-10
  • 2019-08-20
  • 1970-01-01
  • 2022-10-25
  • 2021-09-16
相关资源
最近更新 更多