我有一张表来存储有关我的兔子的信息。它看起来像这样:
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"'
);
我不喜欢那个查询。这是一团糟。
作为一名全职兔子守护者,我没有时间改变我的数据库架构。我只想喂我的兔子。是否有更可读的方式来执行该查询?
答案 0 :(得分:127)
从PostgreSQL 9.4开始,您可以使用?
operator:
select info->>'name' from rabbits where (info->'food')::jsonb ? 'carrots';
如果切换到 jsonb 类型,您甚至可以在?
键上对"food"
查询编制索引:
alter table rabbits alter info type jsonb using info::jsonb;
create index on rabbits using gin ((info->'food'));
select info->>'name' from rabbits where info->'food' ? 'carrots';
当然,你可能没有时间作为全职兔子守护者。
更新:这里展示了1,000,000只兔子的表格,每只兔子喜欢两种食物,其中10%像胡萝卜一样:
d=# -- Postgres 9.3 solution
d=# explain analyze select info->>'name' from rabbits where exists (
d(# select 1 from json_array_elements(info->'food') as food
d(# where food::text = '"carrots"'
d(# );
Execution time: 3084.927 ms
d=# -- Postgres 9.4+ solution
d=# explain analyze select info->'name' from rabbits where (info->'food')::jsonb ? 'carrots';
Execution time: 1255.501 ms
d=# alter table rabbits alter info type jsonb using info::jsonb;
d=# explain analyze select info->'name' from rabbits where info->'food' ? 'carrots';
Execution time: 465.919 ms
d=# create index on rabbits using gin ((info->'food'));
d=# explain analyze select info->'name' from rabbits where info->'food' ? 'carrots';
Execution time: 256.478 ms
答案 1 :(得分:15)
不聪明但更简单:
select info->>'name' from rabbits WHERE info->>'food' LIKE '%"carrots"%';
答案 2 :(得分:12)
一个小变化,但没有新的事实。它确实缺少一个功能...
select info->>'name' from rabbits
where '"carrots"' = ANY (ARRAY(
select * from json_array_elements(info->'food'))::text[]);
答案 3 :(得分:12)
您可以使用@>运营商这样做
SELECT info->>'name'
FROM rabbits
WHERE info->'food' @> '"carrots"';
答案 4 :(得分:0)
不简单但更聪明:
select json_path_query(info, '$ ? (@.food[*] == "carrots")') from rabbits