sql - 如何从 PostgreSQL 中的 jsonb 获取特定对象?

标签 sql json postgresql postgresql-9.5

我有一个名为“测试”的表,其中包含两个字段“qnId”和“答案”。 'qnId' 存储一个 uuid,'Answers' 是一个 jsonb 数组,大致如下所示:

[{ "user" : "1", "ans" : "some text" }, { "user" : "3", "ans": "some text"}]

如何检索 “user”“ans” 的值为 3。 如何使用普通 SQL 查询检索值

最佳答案

尝试这样的事情:

select
    x ->> 'ans' as user_3_ans
from
    jsonb_array_elements('[{ "user" : "1", "ans" : "some text 1" }, { "user" : "3", "ans": "some text 3"}]'::jsonb) as x
where
    x ->> 'user' = '3'

相同,但来自表格:

with

table1 as (
    select
        1 as id,
        '[{ "user" : "1", "ans" : "some text 1" }, { "user" : "3", "ans": "some text 3"}]'::jsonb as answers
)

select
    id,
    answers,
    el ->> 'ans' as user_3_ans
from
    (   select
            id,
            answers,
            jsonb_array_elements(answers) as el
        from
            table1) as x
where
    el ->> 'user' = '3'

关于sql - 如何从 PostgreSQL 中的 jsonb 获取特定对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57339793/

相关文章:

json - Spark 2.0 将 json 读取到键中带有引号的数据帧中 - 与 Spark 1.6 的行为不同... bug?

ios - 在 Objective-C 中解析 JSON 响应字符串

postgresql - 将 ODBC 数据库表链接到 Postgres

php - 将 MySQL 数据分类为限制大小的页面,并在屏幕上选择更改页面?它是如何完成的?

sql - MySQL 数据类型 : int versus enum

javascript - 人们如何在 2013 年验证他们的网站?

php - 无法使用 brew 找到 PHP 的 php72-pdo-pgsql/PostgreSQL 驱动程序

python-3.x - 使用 psycopg2 调用带有自定义类型数组的 postgres 函数

mysql - 将两行合并为一行 - 肮脏且缓慢的过程

mysql - 我如何: ORDER BY COUNT(column1) from the result of: SELECT DISTINCT column1,栏2