PostgreSQL,如何将结果附加到另一个查询结果

时间:2017-02-12 17:09:33

标签: postgresql

首次质询

SELECT * FROM users WHERE _id = 1

来自查询的结果:

{
  username: "Test",
  nickname: "somename"
}

第二次查询

SELECT json_object_agg(permission, true) FROM user_permissions WHERE user_id = 1

来自查询的结果:

{
  add: true,
  delete: true,
  somepermission: true
}

第三次查询

SELECT array_agg(number) FROM user_phone_numbers WHERE user_id = 1

来自查询的结果:

[
  00000-0000-000,
  11111-1111-111
]

基本上我想把第二个和第三个查询的结果放到第一个查询中,所以最终结果将是

{
  username: "Test",
  nickname: "somename"
  customJSONPermission: {
        add: true,
        delete: true,
        somepermission: true
  },
  customerArrayPhone: [
      00000-0000-000,
      11111-1111-111
  ]
}

如何制作单个SQL命令来处理这种操作。我应该查找哪种关键字或功能?

1 个答案:

答案 0 :(得分:2)

您可以将所有查询放在一个:

SELECT u.username,
       u.nikname,
       (SELECT json_object_agg(permission, true) FROM user_permissions WHERE user_id = u._id) AS customJSONPermission,
       (SELECT array_agg(number) FROM user_phone_numbers WHERE user_id = u._id) AS customerArrayPhone
  FROM users AS u
 WHERE u._id = 1