【问题标题】:Postgres JSONB column select statement that handles array and none array entries处理数组和无数组条目的 Postgres JSONB 列选择语句
【发布时间】:2020-11-07 16:23:06
【问题描述】:

我有一个带有电子邮件表的 postgres 数据库,该表有一个 jsonb 列,用于存储电子邮件发送给谁。如果一封电子邮件发送给一个人,它的存储方式类似于

{"name": "bob", "email": "bob@email.com"}

我可以通过这样做来查询这个

select * from email where (to->>'address') = 'bob@email.com'; 

如果电子邮件发送给多个人,则其存储方式如下:

[{"email": "bob@email.com"}, {"email": "dave@email.com"}]

我可以这样查询:

select * from email where to @> '[{"email": "bob@email.com"}]';

我想知道是否有人对可以返回两种方案结果的单个查询有任何想法。

【问题讨论】:

    标签: sql json postgresql where-clause jsonb


    【解决方案1】:

    你可以使用jsonb_typeof():

    select *
    from email
    where 
        (jsonb_typeof(to) = 'object' and to->>'address' = 'bob@email.com')
        or (jsonb_typeof(to) = 'array' and to @> '[{"email": "bob@email.com"}]')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-08
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 2020-10-31
      • 1970-01-01
      相关资源
      最近更新 更多