如何筛选json列中嵌套值的行?

时间:2015-02-16 14:11:00

标签: sql json postgresql nested

这是我的表格(简化的,只有重要的列):

CREATE TABLE things (
  id serial primary key
, name varchar
, blueprint json default '{}'
);

以及一些示例数据:

# select * from things;

 id |  name   |                                  blueprint
----+---------+-----------------------------------------------------------------------------
  1 | Thing 1 | {}
  2 | Thing 2 | {"1":{"name":"Iskapola","wight":"2"}}
  3 | Thing 3 | {"1":{"name":"Azamund","weight":"3"}, "2":{"name":"Iskapola","weight":"1"}}
  4 | Thing 4 | {"1":{"name":"Ulamir","weight":"1"}, "2":{"name":"Azamund","weight":"1"}}

我想在'Azamund'键下选择name位置的行。 像这样:

# select * from things where * ->> 'name' = 'Azamund';

 id |      blueprint
----+----------------------------------------------------------------------------
  7 | {"1":{"name":"Azamund","weight":"3"}, "2":{"name":"Iskapola","weight":"1"}}
  8 | {"1":{"name":"Ulamir","weight":"1"}, "2":{"name":"Azamund","weight":"1"}}

数据的嵌套方式与样本完全相同(只有一个级别) 目前我们正在使用PostgreSQL 9.3.5。

在PostgreSQL 9.3中有可能吗?也许9.4?

2 个答案:

答案 0 :(得分:1)

我可以执行的最接近的查询(返回我需要的数据)是:

select *
from (select id, (json_each(blueprint)).value::json->>'name' as name
      from stocks) as t
where t.name ~* 'azamund';

嗯......也许有更好的东西?

答案 1 :(得分:1)

您的查询已结束。 json_each()是关键功能。或jsonb_each() jsonb 一些改进:

SELECT t.*
FROM   things t, json_each(t.blueprint) b
WHERE  b.value->>'name' ILIKE 'azamund';

SQL Fiddle.

替代JSON数组

您已经看到了我对JSON数组的相关答案:

虽然对嵌套JSON对象的查询看起来同样简单,但对于数组有优越的索引支持