首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何查询json字段类型postgresql中的空值?

如何查询json字段类型postgresql中的空值?
EN

Stack Overflow用户
提问于 2013-10-17 17:16:44
回答 4查看 63.7K关注 0票数 52

我在postgresql中有一个json类型字段。但是,我不能选择特定字段为空的行:

代码:

代码语言:javascript
运行
复制
SELECT *
FROM   json_array_elements(
  '[{"name": "Toby", "occupation": "Software Engineer"},
    {"name": "Zaphod", "occupation": "Galactic President"} ,
{"name2": "Zaphod", "occupation2": null} ]'  ) AS elem
where elem#>'{occupation2}' is null

这应该可以工作,但我得到了这个错误:

代码语言:javascript
运行
复制
ERROR:  operator does not exist: json #> boolean
LINE 6: where elem#>'{occupation2}' is null
EN

回答 4

Stack Overflow用户

发布于 2013-10-17 20:35:23

您可以利用elem->'occupation2'返回json类型的字符串null这一事实,因此您的查询将是:

代码语言:javascript
运行
复制
select
    *
from  json_array_elements(
  '[{"name": "Toby", "occupation": "Software Engineer"},
    {"name": "Zaphod", "occupation": "Galactic President"} ,
    {"name2": "Zaphod", "occupation2": null} ]'
) as elem
where (elem->'occupation2')::text = 'null'

{"name2": "Zaphod", "occupation2": null}

如果你想得到所有的元素,在JSON中值为null或者key不存在,你可以这样做:

代码语言:javascript
运行
复制
select
    *
from  json_array_elements(
  '[{"name": "Toby", "occupation": "Software Engineer"},
    {"name": "Zaphod", "occupation": "Galactic President"} ,
    {"name2": "Zaphod", "occupation2": null} ]'
) as elem
where (elem->>'occupation2') is null

{"name": "Toby", "occupation": "Software Engineer"}
{"name": "Zaphod", "occupation": "Galactic President"}
{"name2": "Zaphod", "occupation2": null}
票数 68
EN

Stack Overflow用户

发布于 2016-01-28 22:56:35

如果您要在json-blob中搜索空值,则可能需要考虑使用Postgres9.4中引入的函数json_typeof(json)

代码语言:javascript
运行
复制
INSERT INTO table
  VALUES ('{ "value": "some", "object": {"int": 1, "nullValue": null}}');

SELECT * FROM table
  WHERE json_typeof(json->'object'->'nullValue') = 'null';

这将导致您找到NULL值的条目。

希望这能有所帮助!

参考:http://www.postgresql.org/docs/9.4/static/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE

票数 12
EN

Stack Overflow用户

发布于 2017-07-11 07:22:24

来自@roman-pekar和@mraxus的答案很有帮助,但我并不满意,因为我没有能力清楚地区分未定义和空...所以,我想出了:

代码语言:javascript
运行
复制
CREATE OR REPLACE FUNCTION isnull (element json)
RETURNS boolean AS $$
  SELECT (element IS NOT NULL) AND (element::text = 'null');
$$ LANGUAGE SQL IMMUTABLE STRICT;

select isnull('{"test":null}'::json->'test'); -- returns t
select isnull('{"test":"notnull"}'::json->'test'); -- returns f
select isnull('{"toot":"testundefined"}'::json->'test'); -- returns null

@a_horse_with_no_name还指出了PostgreSQL9.4版本中引入的额外的jsonb操作符?

代码语言:javascript
运行
复制
SELECT '{"a":1, "b":2}'::jsonb ? 'b'
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19422640

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档