检查postgresjsonb是否包含其中一个值

dgenwo3n  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(367)

我需要检查jsonb字段是数组还是字符串。我拥有的简单数据:

INSERT INTO users (jsonb) VALUES
('{"name":"Henry", "favoritefood_1":["eggs","apples"]}'),
('{"name":"Herald","favoritefood_1":["apples","potatoes"]}'),
('{"name":"Helen", "favoritefood_1":"apples"}');

我该如何找到喜欢苹果和鸡蛋的用户?我尝试了许多查询,最后一个是:

SELECT * FROM users
WHERE CASE
WHEN jsonb_typeof((jsonb->>'favoritefood_1')::jsonb) = 'array'
THEN jsonb_array_elements((jsonb->>'favoritefood_1')::jsonb) IN ('apples', 'eggs')
ELSE (jsonb->>'favoritefood_1')::jsonb IN ('apples', 'eggs') END

有人能帮我吗?

hujrc8aj

hujrc8aj1#

只是 ? 应该工作:

where jsonb -> 'favoritefood_1' ? 'apples'
wnavrhmk

wnavrhmk2#

where jsonb -> 'favoritefood_1' ?| array['apples', 'eggs']

相关问题