【问题标题】:How to search within a jsonb column in postgresql如何在 postgresql 的 jsonb 列中搜索
【发布时间】:2016-07-11 13:37:50
【问题描述】:

我基本上有一个包含 jsonb 类型列的 postgresql 表。 json数据是这样的

{
  "personal": {  
    {
       "gender":"male",
       "contact":{
          "home":{
             "email":"ceo@home.me",
             "phone_number":"5551234"
          },
          "work":{
             "email":"ceo@work.id",
             "phone_number":"5551111"
          }
       },
       "religion":"other",
       "languages":[
          "English",
          "Xen"
       ],
       "last_name":"Eeo",
       "birth_date":"1945-07-28",
       "first_name":"Cee",
       "nationality":"Martian",
       "marital_status":"married"
    }
  }
}

我想获取所有具有“火星人”和“人族”国籍的人......在我的 postgresql 命令行中这是可行的

select employees->'personal'->'contact'->'work'->'email' 
from employees 
where employees->'personal' @> '{"nationality":"Martian"}' 
   or employees->'personal' @> '{"nationality":"Terran"}'

这可行.. 但它很丑.. 我想运行这样的东西:

select employees->'personal'->'contact'->'work'->'email' 
from employees 
where employees->'personal'->'nationality' in ('Martian','Terran')

但我收到这样的格式错误:

DETAIL:  Token "Martian" is invalid.
CONTEXT:  JSON data, line 1: Martian

【问题讨论】:

    标签: postgresql jsonb


    【解决方案1】:

    您必须使用“get value as text”操作符->> 来实现这一点:

    select employees->'personal'->'contact'->'work'->>'email' 
    from employees 
    where employees->'personal'->>'nationality' in ('Martian','Terran')
    

    我还将它添加到获取电子邮件中,因为我假设您希望它作为文本。

    请注意,转换为文本 (employees->'personal'->'nationality')::text 不起作用,因为它不仅返回值,而且将 json 转换为文本,在本例中为 "Martian",包括引号。

    【讨论】:

    【解决方案2】:

    使用->> operator:

    select employees->'personal'->'contact'->'work'->'email' 
    from employees 
    where employees->'personal'->>'nationality' in ('Martian','Terran')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-27
      • 2015-08-15
      • 2020-12-08
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      • 2017-04-23
      相关资源
      最近更新 更多