我的表名为doc_definition
,其json
列definition
的格式如下:
[{
"id":"0",
"name:"Ques1"
},{
"id":"1",
"name:"Ques2"
},{
"id":"2",
"name:"Ques3"
}]
另一个表doc
,其中包含另一个json
列def_val
,其格式为:
{
"0":{
"value":"Ans1"
},
"1":{
"value":"Ans2"
},
"2":{
"value":"Ans3"
}
}
我想创建一个Postgres SQL查询,通过匹配两个json中的id字段来提供相应问题的值。 到目前为止,我已经想出了这个:
SELECT json_array_elements(def.definition) ->> 'name' AS json_test
FROM document_definitions AS def
INNER JOIN documents AS doc
ON doc.document_definition_id = def.id
WHERE doc.id = 892 AND json_array_elements(def.definition) ->> 'name' = 'Ques2'
但这引发了异常:
ERROR: argument of AND must not return a set
当我将json_array_elements(def.definition) ->> 'name' = 'Ques2'
放入SELECT
子句时,它返回布尔值。
我当时不知道什么是错的。 Plz帮助?
答案 0 :(得分:0)
该查询怎么样:
SELECT json_array_elements(def.definition) ->> 'name' AS json_test
FROM document_definitions AS def
INNER JOIN documents AS doc
ON doc.document_definition_id = def.id
WHERE doc.id = 892 AND (json_array_elements(def.definition) ::json->> 'name') = 'Ques2'
答案 1 :(得分:0)
经过多次试验和错误,我已经想出了这个。 如果我能以任何方式改善这一点,请告诉我。
SELECT definition_json.definition_value -> definition_json.def_value_id ->> 'value' AS definition_value
FROM (
SELECT json_array_elements(def.definition) ->> 'name' = 'Ques2' AS is_definition_present,
json_array_elements(def.definition) ->> 'id' AS def_value_id,
doc.definition_value, doc.id AS document_id, def.id AS definition_id
FROM document_definitions AS def
INNER JOIN documents AS doc
ON doc.document_definition_id = def.id
) AS definition_json
WHERE definition_json.is_definition_present = 't' AND definition_json.document_id = 892