【问题标题】:how to check a value of a key is true in postgres jsonb query如何在 postgres jsonb 查询中检查键的值是否为真
【发布时间】:2018-06-17 10:27:54
【问题描述】:

例如我的表是:

CREATE TABLE mytable (
    id bigint NOT NULL,
    foo jsonb
);

它有一些价值:

id   | foo
-----+-------
 1   | "{'a':false,'b':true}"
 2   | "{'a':true,'b':false}"
 3   | NULL

我想知道如何检查一个键的值是否为true,我应该使用哪个operator

我想要这样可以检查值的东西:

SELECT 1 
FROM mytable
WHERE
id=2
AND
foo['a'] is true
;

【问题讨论】:

    标签: sql json postgresql boolean


    【解决方案1】:

    要获取键的text 值,请使用->>(双头),要获取jsonjsonb 值,请使用->(单头)。

    请注意,因为 JSON 布尔值 true 和字符串值 "true"text 表示形式都是 true

    tamlyn=# select '{"a":true}'::json->>'a' bool, '{"a":"true"}'::json->>'a' str;
     bool | str
    ------+------
     true | true
    (1 row)
    

    在你的情况下,你可能想要->

    tamlyn=# select '{"a":true}'::json->'a' bool, '{"a":"true"}'::json->'a' str;
     bool |  str
    ------+--------
     true | "true"
    (1 row)
    

    【讨论】:

      【解决方案2】:
      SELECT 1
      FROM mytable
      Where
      id=2
      AND
      (foo ->> 'a')::boolean is true;
      ;
      

      【讨论】:

        【解决方案3】:

        foo['a'] 语法在 Postgres 中无效。

        如果要访问某个键的值,需要使用->>操作符as documented in the manual

        select *
        from mytable
        where id = 2
        and foo ->> 'a' = 'true';
        

        【讨论】:

        • 请注意,这不会区分布尔值true 和字符串"true"
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-27
        • 2021-12-12
        • 2018-08-16
        • 1970-01-01
        • 2018-07-26
        • 2018-02-13
        • 1970-01-01
        相关资源
        最近更新 更多