gpt4 book ai didi

sql - 如何根据 PostgreSQL 中 JSON 中的另一个字符串从 JSON 中查询一个字符串?

转载 作者:行者123 更新时间:2023-11-29 14:24:48 25 4
gpt4 key购买 nike

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

{
"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'

关于sql - 如何根据 PostgreSQL 中 JSON 中的另一个字符串从 JSON 中查询一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59079358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com