Adding values from one column to two tables in MySQL

2

I'm a beginner in programming and would like to know how to add 1-column values into 2 tables, both with the same data. Just change the table name ...

For example:

Table teste1 :

nome | pontos |
Joao |   10   |

Table teste2 :

nome | pontos |
Joao | 10     |

I want it to return like this:

Nome | Total
Joao |  20

I tried to use JOIN , UNION , UNION ALL and I can not ...

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 ?

    
asked by anonymous 04.01.2019 / 02:23

1 answer

2

Hello, how are you? 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 guarantee that in the two 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 for you too.

Thank you.

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

    
04.01.2019 / 02:56