Cra*_*ing 6 postgresql array json
我有一个表定义为:
create table dummy (jdata jsonb);
Run Code Online (Sandbox Code Playgroud)
我插入了以下两行:
insert into dummy values ('["dog","cat","elephant","waffle"]');
insert into dummy values ('[1,2,3,4]');
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用 jsonb?&
运算符,它可以让您提出问题“所有这些键/元素字符串都存在吗?”
使用字符串字段的示例有效:
select * from dummy where jdata ?& array['cat','dog'];
jdata
--------------------------------------
["dog", "cat", "elephant", "waffle"]
(1 row)
Run Code Online (Sandbox Code Playgroud)
但是,尝试使用包含数字的数组来执行此操作是行不通的:
select * from dummy where jdata ?& array['1','2'];
jdata
-------
(0 rows)
select * from dummy where jdata ?& array['1','2'];
jdata
-------
(0 rows)
select * from dummy where jdata ?& array[1,2];
ERROR: operator does not exist: jsonb ?& integer[]
LINE 1: select * from dummy where jdata ?& array[1,2];
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
Run Code Online (Sandbox Code Playgroud)
我知道该?&
运算符适用于文本数组,但这就是问题所在。有谁知道如何让 json 运算符处理数字数组?
您使用了错误的运算符@>
(在 9.4 中添加)。?&
仅对 JSON 对象进行操作。
SELECT
j,
j @> '"dog"'::jsonb AS hasDog,
j @> '["dog","waffle"]' AS hasDogAndWaffle,
j @> '5' AS has5,
j @> '42' AS has42
FROM ( VALUES
('[5,2,3]'::jsonb),
('["dog","cat","elephant","waffle"]'::jsonb)
)
AS t(j);
j | hasdog | hasdogandwaffle | has5 | has42
--------------------------------------+--------+-----------------+------+-------
[5, 2, 3] | f | f | t | f
["dog", "cat", "elephant", "waffle"] | t | t | f | f
(2 rows)
Run Code Online (Sandbox Code Playgroud)
如果您存储的只是数字,则应该考虑使用intarray
而不是 jsonb。应该会快很多。