如何从两个不同表中的 JSON 数组中查询?

How to query from JSON arrays from two different tables?

我有一个 table 名称 doc_definitionjsondefinition,其格式如下:

[{
  "id":"0",
  "name:"Ques1"
 },{
  "id":"1",
  "name:"Ques2"
 },{
  "id":"2",
  "name:"Ques3"
}]

和另一个 table doc,它有另一个 jsondef_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 子句中时,它是 returns 布尔值。

我不知道怎么了。请帮助?

那个查询怎么样:

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'

经过多次试验和错误,我想到了这个。 如果我能以任何方式改进它,请告诉我。

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