我有一个表来存储我的兔子的信息。它是这样的:
create table rabbits (rabbit_id bigserial primary key, info json not null);
insert into rabbits (info) values
('{"name":"Henry", "food":["lettuce","carrots"]}'),
('{"name":"Herald","food":["carrots","zucchini"]}'),
('{"name":"Helen", "food":["lettuce","cheese"]}');
我该如何找到喜欢吃胡萝卜的兔子呢?我想到了这个:
select info->>'name' from rabbits where exists (
select 1 from json_array_elements(info->'food') as food
where food::text = '"carrots"'
);
我不喜欢这个问题。真是一团糟。
作为一个全职的养兔人,我没有时间更改我的数据库模式。我只是想好好喂养我的兔子。是否有更可读的方式来执行该查询?