在 PostgreSQL 中,如何根据 JSON 中的另一个字符串查询 JSON 中的字符串?

How do I query a string from JSON based on another string within the JSON in PostgreSQL?

MyTable.MyField 在我的 PostgreSQL 数据库中包含以下(简化的)JSON 块:

{
    "base": {
        "fields": [
            {
                "fieldid": "c12f",
                "fieldname": "sizes",
                "choices": [
                    {
                        "choiceid": "2db3",
                        "size": "small"
                    },
                    {
                        "choiceid": "241f",
                        "size": "medium"
                    },
                    {
                        "choiceid": "3f52",
                        "size": "large"
                    }
                ],
                "answer": "241f"
            }
        ]
    }
}

如何使用 answer 的值从 choices 数组中提取所选的 size(即在本例中为 "medium")?

(注意:我试过了。有关此问题的 TLDR 版本,请参阅 Trying to construct PostgreSQL Query to extract from JSON a text value in an object, in an array, in an object, in an array, in an object。)

谢谢。

您可以在横向连接中使用 json_array_elements,然后只需查询您要查找的字段:

SELECT
  field -> 'fieldid' AS id,
  choice -> 'size' AS size
FROM
  my_table,
  json_array_elements(json_column -> 'base' -> 'fields') field,
  json_array_elements(field -> 'choices') choice
WHERE
  field ->> 'answer' = choice ->> 'choiceid'