2017-07-13 43 views
0

我在PostgreSQL中编写SQL查询。我现在有:Postgres json别名

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"}} 

你能告诉我怎样才能得到它呢?

+0

这里'item'只是一个子查询的别名 - 你确定要在JSON别名吗? .. –

+0

这是一个子查询。我需要从少数表中获得相同的结果,然后按顺序对其进行排序。如果我想知道哪个表的哪个结果需要为每个结果使用别名。 项目只是别名。 – Kito

+0

如果'id'是该表的主键,那为什么要使用子查询呢? –

回答

0

你不会需要这样的结果子查询和使用Postgres jsonb functionjsonb_build_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) 
+0

谢谢!这是我需要的。 – Kito