Answer the question
In order to leave comments, you need to log in
How to correctly get data from two tables in one row?
Hello. I've been struggling with a simple question for several days now, I can't find an answer on the Internet (I don't know what wording to use to find the right one).
There are two PostgreSQL tables:
users - list of users
select "users"."id", "users"."name", "socc_acc"."type", "socc_acc"."token" from "users" left join (select "social_id", "user_id", "type", "token" from "socials" where "user_id" = 100) as "socc_acc" on "socc_acc"."user_id" = "users"."id" where "id" = 100 group by "socc_acc"."social_id", "users"."id"
[{
id: 100,
name: 'Haylee Simonis',
type: 1,
token: 'something'
},
{
id: 100,
name: 'Haylee Simonis',
type: 2,
token: 'something2'
}]
select "0"."id", "0"."email", "0"."name, ARRAY_AGG("1"."type") as social_type, ARRAY_AGG("1"."token") as social_token from "users" as "0", "socials" as "1" where "0"."id" = 100 and "1"."user_id" = 100 group by "0"."id"
[{
id: 100,
email: '[email protected]',
name: 'Haylee Simonis',
social_type: [ 2, 1 ],
social_token: [ 'something2', 'something' ]
}]
[{
id: 100,
email: '[email protected]',
name: 'Haylee Simonis',
socials: [{
type: 1,
token: 'something'
},
{
type: 2,
token: 'something2'
}]
}]
SELECT "social_id", array_agg('[' || type || ',' || token || ']') AS "socials" FROM "socials" WHERE "user_id" = 105 GROUP BY "social_id";
socials: [
'[2,something2]',
'[1,something]'
]
Answer the question
In order to leave comments, you need to log in
After three days of searching, I finally came up with this solution, maybe it will be useful to someone:
json_build_object takes as arguments the name of the key for the object and the value (the name of the key in the table) separated by commas.
Result:
[
{ type: 2, token: 'something2' },
{ type: 1, token: 'something' }
]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question