具有嵌套连接的PostgreSQL 9.2 row_to_json()

时间:2012-11-05 06:41:01

标签: json postgresql postgresql-9.2 scalar-subquery

我正在尝试使用PostgreSQL 9.2中添加的row_to_json()函数将查询结果映射到JSON。

我无法找出将连接行表示为嵌套对象(1:1关系)的最佳方法

这是我尝试过的(设置代码:表格,示例数据,然后是查询):

-- some test tables to start out with:
create table role_duties (
    id serial primary key,
    name varchar
);

create table user_roles (
    id serial primary key,
    name varchar,
    description varchar,
    duty_id int, foreign key (duty_id) references role_duties(id)
);

create table users (
    id serial primary key,
    name varchar,
    email varchar,
    user_role_id int, foreign key (user_role_id) references user_roles(id)
);

DO $$
DECLARE duty_id int;
DECLARE role_id int;
begin
insert into role_duties (name) values ('Script Execution') returning id into duty_id;
insert into user_roles (name, description, duty_id) values ('admin', 'Administrative duties in the system', duty_id) returning id into role_id;
insert into users (name, email, user_role_id) values ('Dan', 'someemail@gmail.com', role_id);
END$$;

查询本身:

select row_to_json(row)
from (
    select u.*, ROW(ur.*::user_roles, ROW(d.*::role_duties)) as user_role 
    from users u
    inner join user_roles ur on ur.id = u.user_role_id
    inner join role_duties d on d.id = ur.duty_id
) row;

我发现如果我使用ROW(),我可以将结果字段分成一个子对象,但它似乎仅限于一个级别。我无法插入更多AS XXX语句,因为我认为在这种情况下我需要这些语句。

我获得了列名,因为我转换为适当的记录类型,例如::user_roles,就该表的结果而言。

以下是该查询返回的内容:

{
   "id":1,
   "name":"Dan",
   "email":"someemail@gmail.com",
   "user_role_id":1,
   "user_role":{
      "f1":{
         "id":1,
         "name":"admin",
         "description":"Administrative duties in the system",
         "duty_id":1
      },
      "f2":{
         "f1":{
            "id":1,
            "name":"Script Execution"
         }
      }
   }
}

我想要做的是为连接生成JSON(再次1:1很好),我可以添加连接,并将它们表示为它们加入的父对象的子对象,即如下所示: / p>

{
   "id":1,
   "name":"Dan",
   "email":"someemail@gmail.com",
   "user_role_id":1,
   "user_role":{
         "id":1,
         "name":"admin",
         "description":"Administrative duties in the system",
         "duty_id":1
         "duty":{
            "id":1,
            "name":"Script Execution"
         }
      }
   }
}

感谢任何帮助。谢谢你的阅读。

3 个答案:

答案 0 :(得分:119)

更新:在PostgreSQL 9.4中,这提高了很多with the introduction of to_json, json_build_object, json_object and json_build_array,但由于需要明确命名所有字段,所以它很冗长:

select
        json_build_object(
                'id', u.id,
                'name', u.name,
                'email', u.email,
                'user_role_id', u.user_role_id,
                'user_role', json_build_object(
                        'id', ur.id,
                        'name', ur.name,
                        'description', ur.description,
                        'duty_id', ur.duty_id,
                        'duty', json_build_object(
                                'id', d.id,
                                'name', d.name
                        )
                )
    )
from users u
inner join user_roles ur on ur.id = u.user_role_id
inner join role_duties d on d.id = ur.duty_id;

对于旧版本,请继续阅读。


它不仅限于一排,它只是有点痛苦。您不能使用AS别名复合行类型,因此您需要使用别名子查询表达式或CTE来实现此效果:

select row_to_json(row)
from (
    select u.*, urd AS user_role
    from users u
    inner join (
        select ur.*, d
        from user_roles ur
        inner join role_duties d on d.id = ur.duty_id
    ) urd(id,name,description,duty_id,duty) on urd.id = u.user_role_id
) row;

通过http://jsonprettyprint.com/生成:

{
  "id": 1,
  "name": "Dan",
  "email": "someemail@gmail.com",
  "user_role_id": 1,
  "user_role": {
    "id": 1,
    "name": "admin",
    "description": "Administrative duties in the system",
    "duty_id": 1,
    "duty": {
      "id": 1,
      "name": "Script Execution"
    }
  }
}

当你有1:很多关系时,你会想要使用array_to_json(array_agg(...)),顺便说一句。

理想情况下,上述查询应该写成:

select row_to_json(
    ROW(u.*, ROW(ur.*, d AS duty) AS user_role)
)
from users u
inner join user_roles ur on ur.id = u.user_role_id
inner join role_duties d on d.id = ur.duty_id;

...但是PostgreSQL的ROW构造函数不接受AS列别名。不幸的是

谢天谢地,他们优化了同样的东西。比较计划:

因为CTE是优化围栏,所以将嵌套子查询版本改为使用链式CTE(WITH表达式)可能不会执行,并且不会产生相同的计划。在这种情况下,你会遇到丑陋的嵌套子查询,直到我们对row_to_json进行一些改进或者更直接地覆盖ROW构造函数中的列名称。


无论如何,一般来说,原则是你想用列a, b, c创建一个json对象,你希望你可以写出非法的语法:

ROW(a, b, c) AS outername(name1, name2, name3)

您可以使用标量子查询返回行类型值:

(SELECT x FROM (SELECT a AS name1, b AS name2, c AS name3) x) AS outername

或者:

(SELECT x FROM (SELECT a, b, c) AS x(name1, name2, name3)) AS outername

此外,请注意,您可以撰写json值,而无需额外引用,例如:如果您将json_agg的输出放在row_to_json内,则内部json_agg结果将不会被引用为字符串,它将直接合并为json。

e.g。在任意例子中:

SELECT row_to_json(
        (SELECT x FROM (SELECT
                1 AS k1,
                2 AS k2,
                (SELECT json_agg( (SELECT x FROM (SELECT 1 AS a, 2 AS b) x) )
                 FROM generate_series(1,2) ) AS k3
        ) x),
        true
);

输出是:

{"k1":1,
 "k2":2,
 "k3":[{"a":1,"b":2}, 
 {"a":1,"b":2}]}

请注意,json_agg产品[{"a":1,"b":2}, {"a":1,"b":2}]尚未再次转义,因为text会是。

这意味着您可以撰写 json操作来构造行,您不必总是创建非常复杂的PostgreSQL复合类型,然后在输出上调用row_to_json

答案 1 :(得分:1)

我对长期可维护性的建议是使用VIEW构建查询的粗略版本,然后使用如下函数:

CREATE OR REPLACE FUNCTION fnc_query_prominence_users( )
RETURNS json AS $$
DECLARE
    d_result            json;
BEGIN
    SELECT      ARRAY_TO_JSON(
                    ARRAY_AGG(
                        ROW_TO_JSON(
                            CAST(ROW(users.*) AS prominence.users)
                        )
                    )
                )
        INTO    d_result
        FROM    prominence.users;
    RETURN d_result;
END; $$
LANGUAGE plpgsql
SECURITY INVOKER;

在这种情况下,对象prominence.users是一个视图。由于我选择了用户。*,如果我需要更新视图以在用户记录中包含更多字段,我将不必更新此功能。

答案 2 :(得分:1)

我添加此解决方案是因为接受的响应未考虑N:N关系。 aka:对象集合的集合

如果您有N:N关系,则克劳拉with是您的朋友。 在我的示例中,我想构建以下层次结构的树视图。

A Requirement - Has - TestSuites
A Test Suite - Contains - TestCases.

以下查询代表联接。

SELECT reqId ,r.description as reqDesc ,array_agg(s.id)
            s.id as suiteId , s."Name"  as suiteName,
            tc.id as tcId , tc."Title"  as testCaseTitle

from "Requirement" r 
inner join "Has"  h on r.id = h.requirementid 
inner join "TestSuite" s on s.id  = h.testsuiteid
inner join "Contains" c on c.testsuiteid  = s.id 
inner join "TestCase"  tc on tc.id = c.testcaseid
  GROUP BY r.id, s.id;

由于不能进行多个聚合,因此需要使用“ WITH”。

with testcases as (
select  c.testsuiteid,ts."Name" , tc.id, tc."Title"  from "TestSuite" ts
inner join "Contains" c on c.testsuiteid  = ts.id 
inner join "TestCase"  tc on tc.id = c.testcaseid

),                
requirements as (
    select r.id as reqId ,r.description as reqDesc , s.id as suiteId
    from "Requirement" r 
    inner join "Has"  h on r.id = h.requirementid 
    inner join "TestSuite" s on s.id  = h.testsuiteid

    ) 
, suitesJson as (
 select  testcases.testsuiteid,  
       json_agg(
                json_build_object('tc_id', testcases.id,'tc_title', testcases."Title" )
            ) as suiteJson
    from testcases 
    group by testcases.testsuiteid,testcases."Name"
 ),
allSuites as (
    select has.requirementid,
           json_agg(
                json_build_object('ts_id', suitesJson.testsuiteid,'name',s."Name"  , 'test_cases', suitesJson.suiteJson )
            ) as suites
            from suitesJson inner join "TestSuite" s on s.id  = suitesJson.testsuiteid
            inner join "Has" has on has.testsuiteid  = s.id
            group by has.requirementid
),
allRequirements as (
    select json_agg(
            json_build_object('req_id', r.id ,'req_description',r.description , 'test_suites', allSuites.suites )
            ) as suites
            from allSuites inner join "Requirement" r on r.id  = allSuites.requirementid

)
 select * from allRequirements

它的作用是在少量项目中构建JSON对象,并将其聚集在每个with子句中。

结果:

[
  {
    "req_id": 1,
    "req_description": "<character varying>",
    "test_suites": [
      {
        "ts_id": 1,
        "name": "TestSuite",
        "test_cases": [
          {
            "tc_id": 1,
            "tc_title": "TestCase"
          },
          {
            "tc_id": 2,
            "tc_title": "TestCase2"
          }
        ]
      },
      {
        "ts_id": 2,
        "name": "TestSuite",
        "test_cases": [
          {
            "tc_id": 2,
            "tc_title": "TestCase2"
          }
        ]
      }
    ]
  },
  {
    "req_id": 2,
    "req_description": "<character varying> 2 ",
    "test_suites": [
      {
        "ts_id": 2,
        "name": "TestSuite",
        "test_cases": [
          {
            "tc_id": 2,
            "tc_title": "TestCase2"
          }
        ]
      }
    ]
  }
]