Bringing together records from another table in a new query

Asked

Viewed 35 times

0

I have a table "tbA" where the primary column "a1" needs to be referenced by the table "tbB" by the column "fk_a1"

tbA

id | nome   |
---+------+--
1,  'aaaa'
2,  'bbbbb'
3,  'cccc'
4,  'ddddd'

tbB

id | fk_a1 |  valor_1 | valor_2 |
---+-------+----------+----------
1,     2,     500.00,    100.00
2,     1,     150.00,    200.00
3,     1,     100.00,    50.00
4,     3,     10.00,     0.00
5,     3,     100.00,     20.00

Whereas the relationship between the two tables is something like

SELECT * FROM tbA a LEFT JOIN tbB b ON b.fk_a1 = a.id

Once this relationship is done, list the records considering that the main table is tbA and the added values of tbB will come in the list like this

id | nome |  soma_1 | soma_2 |
---+------+---------+---------
1,  'aaaa',   250.00,  50.00
2,  'bbbbb',  500.00,  100.00
3,  'cccc',   110.00,  20.00
4,  'ddddd',  0.00,    0.00

I don’t know exactly how to do this, thank you.

1 answer

1


It would be something +- like this:

SELECT id,nome,SUM(valor_1) as soma_1, SUM(valor_2) as soma2 
FROM tbA a JOIN tbB
ON b.fk_a1 = a.id, GROUP BY a.id

I removed the LEFT because then it would have no effect.

  • In my case I needed the left because I also need to bring records that do not exist from the daughter table, thanks for the help, worked perfectly :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.