Add one column values to two tables in Mysql

Asked

Viewed 115 times

2

I am a beginner in programming and I would like to know how to add values of 1 column in 2 tables, both with the same data. Just rename the table...

For example:

Table teste1:

nome | pontos |
Joao |   10   |

Table teste2:

nome | pontos |
Joao | 10     |

I want you to come back like this:

Nome | Total
Joao |  20

I tried to use JOIN, UNION, UNION ALL and I can’t...

I used:

SELECT nome AS nome, pontos AS total from teste1 where nome = 'Joao'
UNION ALL
SELECT nome AS nome, pontos AS total from teste2 where nome = 'Joao'

To which my return is:

nome  |  total
Joao  |   10
Joao  |   10

How to return the total of this query: 10 + 10?

1 answer

2


Hello, all right? Although I have been using the community for many years, I am also a new user, but I will try to contribute...

There are a few ways to do this, but a "simple" way is to add the two int columns and use an INNER JOIN to group them by the NAME field.

SELECT teste1.pontos+teste2.pontos AS total FROM teste1 INNER JOIN teste2 ON(teste1.nome = teste2.nome) WHERE teste1.nome="joao"

When we use INNER JOIN we ensure that in both tables there are values for those fields and that they are the same... I advise you to read further, but there are LEFT JOIN, RIGHT JOIN, other approaches that may be interesting to you too.

Thank you.

ps: I did not test the code, I did based on your select.

  • 1

    You’ve helped me a lot, thank you very much!!!

Browser other questions tagged

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