gpt4 book ai didi

postgresql - 测试 Postgres json 数组中的项目成员资格

转载 作者:行者123 更新时间:2023-11-29 12:29:56 24 4
gpt4 key购买 nike

假设我在 Postgres 中有一个看起来像这样的表 - 请注意 zips 字段是 json。

cities
name (text) | zips (json)
San Francisco | [94100, 94101, ...]
Washington DC | [20000, 20001, ...]

现在我想做一些事情,比如 select * from cities where zip=94101,换句话说,测试成员资格。

我试过使用 WHERE zipper ? '94101' 并得到 operator does not exist: json ?未知

我尝试使用 WHERE zips->'94101' 但不确定要放什么,因为 Postgres 提示 WHERE 的参数必须是 boolean 类型,而不是 json 类型 .

我在这里想要什么?对于 9.3 和 9.4,我该如何解决这个问题?

编辑 是的,我知道我应该使用 native 数组类型...我们使用的数据库适配器不支持这个。

最佳答案

在 PostgreSQL 9.4+ 中,您可以使用 @> 运算符和 jsonb 类型:

create table test (city text, zips jsonb);
insert into test values ('A', '[1, 2, 3]'), ('B', '[4, 5, 6]');
select * from test where zips @> '[1]';

这种方法的另一个优势是 9.4 的新 GIN indexes这加快了对大表的此类查询。

关于postgresql - 测试 Postgres json 数组中的项目成员资格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27912776/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com