【问题标题】:How to query Postgres JSONB arrays with = operator如何使用 = 运算符查询 Postgres JSONB 数组
【发布时间】:2019-03-05 13:55:31
【问题描述】:

我正在寻找一种使用 = 子句查询 PostgreSQL JSONB 数组字段的方法。

假设我有一张桌子

CREATE TABLE events(
   id integer,
   tags jsonb,
   PRIMARY KEY(id)
);

标签的值类似于['Google', 'Hello World', 'Ruby']

我经历过Stackover Flow,也做过类似的事情。

而形成的SQL是这样的

SELECT "events".* FROM "events" WHERE ("events"."tags" @> '{google}')  ORDER BY "business_events"."id" desc;

通过运行这个,我得到了这个错误 =>

ERROR:  invalid input syntax for type json
LINE 1: ...siness_events" WHERE ("business_events"."tags" @> '{google}'...
                                                             ^
DETAIL:  Token "google" is invalid.
CONTEXT:  JSON data, line 1: {google...

有什么想法吗?

【问题讨论】:

    标签: postgresql activeadmin jsonb


    【解决方案1】:

    the operator @> 的右操作数应该是有效的json

    WITH events(id, tags) AS (
    VALUES
        (1, '["Google", "Hello World", "Ruby"]'::jsonb)
    )
    
    SELECT events.* 
    FROM events 
    WHERE tags @> '["Google"]'
    
     id |               tags                
    ----+-----------------------------------
      1 | ["Google", "Hello World", "Ruby"]
    (1 row)
    

    请注意,json 对象的键和文本值用双引号括起来。

    运算符按原样接受参数,并且无法使其不区分大小写。您可以使用函数jsonb_array_elements_text() 来完成此操作:

    SELECT events.*
    FROM events 
    CROSS JOIN jsonb_array_elements_text(tags)
    WHERE lower(value) = 'google';
    

    第二种解决方案要贵得多,the cited answer 中的注释也适用于此。

    【讨论】:

    • 如何使它不区分大小写?有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    • 2022-01-02
    • 2018-03-29
    • 2017-02-05
    • 2015-11-28
    • 2015-09-10
    • 2016-06-14
    相关资源
    最近更新 更多