Sno*_*all 86 postgresql json postgresql-9.3
我有一张桌子来存储关于我的兔子的信息.它看起来像这样:
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"]}');
Run Code Online (Sandbox Code Playgroud)
我该怎么找到喜欢胡萝卜的兔子?我想出了这个:
select info->>'name' from rabbits where exists (
select 1 from json_array_elements(info->'food') as food
where food::text = '"carrots"'
);
Run Code Online (Sandbox Code Playgroud)
我不喜欢那个查询.一团糟.
作为一名全职兔子守护者,我没有时间改变我的数据库架构.我只想喂我的兔子.是否有更可读的方式来执行该查询?
Sno*_*all 143
从PostgreSQL 9.4开始,您可以使用?运算符:
select info->>'name' from rabbits where (info->'food')::jsonb ? 'carrots';
Run Code Online (Sandbox Code Playgroud)
如果切换到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';
Run Code Online (Sandbox Code Playgroud)
当然,作为一名全职兔子守门员,你可能没有时间.
更新:这里展示了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
Run Code Online (Sandbox Code Playgroud)
chr*_*mod 17
不聪明但更简单:
select info->>'name' from rabbits WHERE info->>'food' LIKE '%"carrots"%';
Run Code Online (Sandbox Code Playgroud)
gor*_*ori 17
您可以使用@>运算符来执行此操作
SELECT info->>'name'
FROM rabbits
WHERE info->'food' @> '"carrots"';
Run Code Online (Sandbox Code Playgroud)
小智 16
如果数组位于 jsonb 列的根部,则 ie 列如下所示:
| 食物 |
|---|
| [“生菜”、“胡萝卜”] |
| [“胡萝卜”、“西葫芦”] |
只需直接在括号内使用列名称即可:
select * from rabbits where (food)::jsonb ? 'carrots';
Run Code Online (Sandbox Code Playgroud)
mac*_*ias 12
一个小的变化,但没有什么新的事实.它真的缺少一个功能......
select info->>'name' from rabbits
where '"carrots"' = ANY (ARRAY(
select * from json_array_elements(info->'food'))::text[]);
Run Code Online (Sandbox Code Playgroud)
为了选择JSONB中的特定键,您应该使用->。
select * from rabbits where (info->'food')::jsonb ? 'carrots';
Run Code Online (Sandbox Code Playgroud)
如果您想检查完整的 json 而不是一个键,您可以直接从 jsonb 进行类型转换为文本。
select * from table_name
where
column_name::text ilike '%Something%';
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
66094 次 |
| 最近记录: |