Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 在Postgres 9.6中查询json列中属性数组内的数据_Sql_Json_Postgresql - Fatal编程技术网

Sql 在Postgres 9.6中查询json列中属性数组内的数据

Sql 在Postgres 9.6中查询json列中属性数组内的数据,sql,json,postgresql,Sql,Json,Postgresql,我有一个表say types,它有一个JSON列,say location,如下所示: { "attribute":[ { "type": "state", "value": "CA" }, { "type": "distance", "value": "200.00" } ... ] } 表中的每一行都有数据,并且其中都有type:state。我只想从表中的每一行提取type:state的值,并将其放入一个新列中。我问了几个问题,比如

我有一个表say types,它有一个JSON列,say location,如下所示:

{ "attribute":[
  {
    "type": "state",
    "value": "CA"
  },
  {
    "type": "distance",
    "value": "200.00"
  } ...
  ]
  } 
表中的每一行都有数据,并且其中都有type:state。我只想从表中的每一行提取type:state的值,并将其放入一个新列中。我问了几个问题,比如:


但无法让它工作。我不需要对此提出质疑。我需要这个列的值。如果我错过了一些东西,我会提前道歉。

我主要使用红移,其中有一个内置函数来完成这项工作。所以如果你不可能在那里,那就去看看吧。

Postgres似乎有一个类似的功能集:

我认为您需要将三个功能链接在一起才能使其正常工作

SELECT 
   your_field::json->'attribute'->0->'value'
FROM
    your_table
我尝试的是按键名进行json提取,如果您的示例与完整数据一致,那么后面总是按索引进行json数组提取,最后是按键名进行另一次提取

编辑:让它为你的例子工作

返回CA

第二次编辑:嵌套查询 @McNets是正确的、更好的答案。但是在这次潜水中,我发现你可以在Postgres中嵌套查询!太酷了

我将json作为文本字段存储在一个虚拟表中,并成功运行了以下操作:

SELECT 
  (SELECT value FROM json_to_recordset(
    my_column::json->'attribute') as x(type text, value text)
  WHERE
    type = 'state'
    )
FROM dummy_table

dbfiddle

是否始终在第一个数组元素中?是否可以有多个type=state的数组元素?不在同一行中。每一行只有一个type=state的属性。谢谢@a_horse_,没有名称,但我不能依赖索引。它可以位于阵列中的任何位置。
SELECT 
  (SELECT value FROM json_to_recordset(
    my_column::json->'attribute') as x(type text, value text)
  WHERE
    type = 'state'
    )
FROM dummy_table
create table t(data json);
insert into t values('{"attribute":[{"type": "state","value": "CA"},{"type": "distance","value": "200.00"}]}'::json); 

select elem->>'value' as state
from t, json_array_elements(t.data->'attribute') elem
where elem->>'type' = 'state';
| state | | :---- | | CA |