0

First Query

SELECT * FROM users WHERE _id = 1

result from query:

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

Second Query

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

result from query:

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

Third Query

SELECT array_agg(number) FROM user_phone_numbers WHERE user_id = 1

result from query:

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

Basically I want to put the result of second and third query into first query so the final result will be

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

How do craft a single SQL command to handle this kind of operation. What kind of keywords or function I should look up?

3
  • Are you familiar with JOIN? Commented Feb 12, 2017 at 17:12
  • Hi this is not exactly JOIN right? JOIN will produce many rows. I just need one row with appended fields Commented Feb 12, 2017 at 17:32
  • I think this can help: hashrocket.com/blog/posts/… Commented Feb 12, 2017 at 17:45

1 Answer 1

3

You can just put all queries in one:

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for this! I guess this is absolutely the shortest way? What if my userobject have 100 fields must I write a really long SQL just to put u.field1, u.field2 ... u.field100?
You can use u.* if you want to get all fields in table
Perfect! Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.