【发布时间】:2013-11-24 09:26:17
【问题描述】:
我有一张表来存储关于我的兔子的信息。它看起来像这样:
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"'
);
我不喜欢那个查询。真是一团糟。
作为一名全职养兔人,我没有时间更改我的数据库架构。我只想好好喂养我的兔子。有没有更易读的方式来做这个查询?
【问题讨论】:
-
有趣的问题。我玩过它,但后来我突然意识到,我不确定你所说的“更好”是什么意思。你用什么标准来判断你的答案?可读性?效率?其他?
-
@DavidS:(我更新了问题。)我更喜欢可读性而不是效率。我当然不希望有什么比全表扫描更好的了,因为我的架构是固定的。
标签: json postgresql postgresql-9.3