我在postgres中有一个表,在一个名为data
的jsonb
列中有如下行:
{ "block": { "data": null, "timestamp": "1680617159" } }
{"block": {"hash": "0xf0cab6f80ff8db4233bd721df2d2a7f7b8be82a4a1d1df3fa9bbddfe2b609e28", "size": "0x21b", "miner": "0x0d70592f27ec3d8996b4317150b3ed8c0cd57e38", "nonce": "0x1a8261f25fc22fc3", "number": "0x1847", "uncles": [], "gasUsed": "0x0", "mixHash": "0x864231753d23fb737d685a94f0d1a7ccae00a005df88c0f1801f03ca84b317eb", "gasLimit": "0x1388", "extraData": "0x476574682f76312e302e302f6c696e75782f676f312e342e32", "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "stateRoot": "0x2754a138df13677ca025d024c6b6ac901237e2bf419dda68d9f9519a69bfe00e", "timestamp": "0x55baa522", "difficulty": "0x3f5a9c5edf", "parentHash": "0xf50f292263f296897f15fa87cb85ae8191876e90e71ab49a087e9427f9203a5f", "sealFields": [], "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", "receiptsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", "transactions": [], "totalDifficulty": "0x239b3c909daa6", "transactionsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"}, "transaction_receipts": []}
我想写一个SQL查询,它选择所有具有block.data
的null
值的行,但不选择没有data
字段的行。
我尝试了以下方法,但都失败了:
SELECT * FROM table WHERE data->>'block'->>'data' IS NULL;
SELECT * FROM table WHERE data->'block'->'data' IS NULL;
SELECT * FROM table WHERE jsonb_extract_path_text(data, 'block', 'data') IS NULL;
看起来在所有这些情况下,如果data
字段不存在,它将传递where
子句。
3条答案
按热度按时间llew8vvj1#
在以下条件下使用
'null'::jsonb
:其他的答案,无论多么有效,都是不必要的复杂,隐藏了事物的本质。问题是
'null'::jsonb
与Postgresnull
不同:你可以使用一个简单的btree索引,它可以支持第一个查询:
或者,gin索引可以支持
@>
运算符:xdnvmnnf2#
您可以使用'@〉'操作符来检查
'{"data":null}'
是否包含在data-〉'block'路径中。输出:
检查here演示。
wkftcu5l3#
使用两个 predicate 查看键是否存在 * 以及值是否为
null
示例
此查询将导致表的
Seq Scan
,如下所示如果定义了
data
键的行数非常少,则可以从索引中获益该计划使用了索引,并且性能更高