Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql Postgres json别名_Sql_Json_Postgresql - Fatal编程技术网

Sql Postgres json别名

Sql Postgres json别名,sql,json,postgresql,Sql,Json,Postgresql,我用PostgreSQL编写SQL查询。我现在: SELECT T.order, (SELECT row_to_json(item) FROM ( SELECT T.title, T.subtitle, T.text FROM table T WHERE T.id = 1 ) AS item) FROM table T WHERE T.id = 1; 结果是: order | row_to_json

我用PostgreSQL编写SQL查询。我现在:

SELECT T.order,
 (SELECT row_to_json(item) FROM (
    SELECT T.title, T.subtitle, T.text
     FROM table T
     WHERE T.id = 1
) AS item)
FROM table T
WHERE T.id = 1;
结果是:

order |               row_to_json                                                         

---------------+------------------------------------------------------
    2 | {"title":"AAA","subtitle":"aaaa","text":"aaaa"}
但我需要结果:

order |               row_to_json                                                         

---------------+------------------------------------------------------
    2 | {"item":{"title":"AAA","subtitle":"aaaa","text":"aaaa"}}

您能告诉我如何获得它吗?

您不需要子查询来获得这样的结果,使用
jsonb\u build\u object
您可以实现这样的目标:

-- Test data:
WITH    "table"( id, "order", title, subtitle, "text" ) AS (
            VALUES  (   1::int, 2::int, 'AAA'::text, 'aaaa'::text, 'aaaa'::text),
                    (   2::int, 3::int, 'BBB'::text, 'bbbb'::text, 'bbbb'::text)
        )
-- The query:
SELECT  "order",
        jsonb_build_object(
            'items',
            jsonb_build_object(
                'title', title,
                'subtitle', subtitle,
                'text', "text"
            )
        ) AS myjson
FROM    "table"
WHERE   id = 1;

-- Result:
 order |                             myjson
-------+-----------------------------------------------------------------
     2 | {"items": {"text": "aaaa", "title": "AAA", "subtitle": "aaaa"}}
(1 row)

这里的
item
只是一个子查询别名-您确定要在json中使用别名吗?它是一个子查询。我需要从几个表中得到相同的结果,然后按顺序排序。如果我想知道哪个表中的哪个结果,我需要每个结果都有别名。项只是别名。如果
id
是该表的主键,那么为什么要使用子查询呢?谢谢!这正是我需要的。