I need to make a SELECT query in PostgreSQL that return data of two tables and multiple rows of a third one.
Table A:
id | serviceId | requestId | description |
---|---|---|---|
1 | 1 | 4 | row |
2 | 2 | 5 | row |
Table B:
serviceId | title |
---|---|
1 | row |
2 | row |
Table C:
requestId | seq | description |
---|---|---|
4 | 1 | row |
4 | 2 | row |
5 | 1 | row |
5 | 2 | row |
I need the following kind of return:
[{
id: 1,
serviceId: 1,
requestId:4,
description: 'row',
title: 'row',
request: [{
requestId: 4,
seq:1,
description: 'row'
},
{
requestId: 5,
seq:2,
description: 'row'
}]
}]
The point is that i need to get multiple rows from the "C" table nested in the response. The JSON is an example to illustrate the case, It doesn't have to be exactly that way. I'm in nodejs with pg library.
It would be possible to make it on a single query? Or databases doesn't response that way of nested rows and i've to do it by two querys?
I have this (incomplete) query:
SELECT A.* , B.*
FROM A
INNER JOIN service ON A."serviceId"= B."serviceId"
WHERE A.id=1
The condition for the "C" table would be:
A."requestId" = C."requestId"