我有一个表来存储我的兔子的信息。它是这样的:

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"'
);

我不喜欢这个问题。真是一团糟。

作为一个全职的养兔人,我没有时间更改我的数据库模式。我只是想好好喂养我的兔子。是否有更可读的方式来执行该查询?


不是更聪明,而是更简单:

select info->>'name' from rabbits WHERE info->>'food' LIKE '%"carrots"%';

一个小的变化,但没有什么新的。它真的缺少了一个功能……

select info->>'name' from rabbits 
where '"carrots"' = ANY (ARRAY(
    select * from json_array_elements(info->'food'))::text[]);

从PostgreSQL 9.4开始,您可以使用?接线员:

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';

当然,作为一个全职的养兔人,你可能没有时间做这些。

更新:下面是在一张有100万只兔子的桌子上演示的性能改进,每只兔子喜欢两种食物,其中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

你可以使用@>操作符来做这样的事情

SELECT info->>'name'
FROM rabbits
WHERE info->'food' @> '"carrots"';

不是更简单,而是更聪明:

select json_path_query(info, '$ ? (@.food[*] == "carrots")') from rabbits

如果数组在jsonb列的根,即列看起来像:

food
["lettuce", "carrots"]
["carrots", "zucchini"]

只需直接在括号内使用列名:

select * from rabbits where (food)::jsonb ? 'carrots';

这可能会有所帮助。

SELECT a.crops ->> 'contentFile' as contentFile
FROM ( SELECT json_array_elements('[
    {
        "cropId": 23,
        "contentFile": "/menu/wheat"
    },
    {
        "cropId": 25,
        "contentFile": "/menu/rice"
    }
]') as crops ) a
WHERE a.crops ->> 'cropId' = '23';

输出:

/menu/wheat

你可以做一个直接类型转换,从jsonb到文本,如果你想检查完整的json而不是一个键。

select * from table_name
where 
column_name::text ilike '%Something%';

为了在JSONB中选择特定的键,应该使用->。

select * from rabbits where (info->'food')::jsonb ? 'carrots';