【问题标题】:Get records where json column key is null获取json列键为空的记录
【发布时间】:2014-07-17 16:24:42
【问题描述】:

我有表 users 和 json 列 details

我想获取 details["email"] 为 null 或电子邮件密钥不存在的所有用户记录。

这不起作用:

SELECT users.* FROM users where details->'email' IS NOT NULL;

ERROR: operator does not exist: json -> boolean

【问题讨论】:

    标签: json postgresql


    【解决方案1】:

    使用括号()。看起来编译器试图将其视为details->('email' IS NOT NULL)。所以你可以这样修复它:

    select *
    from users
    where (details->'email') is not null
    

    sql fiddle demo

    实际上,要获取 details["email"] 为 null 或电子邮件键不存在的记录,您可以使用以下查询:

    select *
    from users
    where (details->>'email') is null
    

    this answer 中所述。

    【讨论】:

    • 完全正确 - 缺少括号。谢谢。
    • 只是为了后代:从 9.5 开始的 Postgres 版本不需要括号。
    【解决方案2】:

    您需要为此使用->> 运算符:

    select *
    from users
    where (details->>'email') is not null
    

    因为-> 运算符返回'null'::json(而不是sql NULL),如果键存在但具有json null 值。

    http://sqlfiddle.com/#!15/76ec4/2

    【讨论】:

    • 实际上问题出在stackoverflow.com/a/23912628/298554中回答的括号缺失
    • 我尝试了->->> - 它总是返回正确的记录。
    • @morgoth 这只是句法问题。如果想要将'null'::json 值与sql 的NULL 相同,他们应该使用->> 运算符而不是->。看看我的小提琴有什么不同。
    • 缺少括号也是我的问题。
    猜你喜欢
    • 1970-01-01
    • 2014-06-29
    • 2019-04-09
    • 2013-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    相关资源
    最近更新 更多