簡體   English   中英

如何基於PostgreSQL中JSON中的另一個字符串從JSON查詢字符串?

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

我的PostgreSQL數據庫中的MyTable.MyField包含以下(簡化的)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 (即本例中的“中”)?

(注意:我已經嘗試過。有關此問題的TLDR版本,請參閱嘗試構造PostgreSQL查詢以從JSON中提取對象,數組,對象,數組,對象中的文本值 。)

謝謝。

您可以在橫向json_array_elements中使用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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM