Borsn Borsn - 3 months ago 10
MySQL Question

MySQL SUM values from 2 tables and JOIN

I have two tables and both

table2
and
table3
may contain an amount for the
key
from table1.

I would like to sum up these values and represent them as
amount
.

SELECT table1.mg_key
, table1.mg_name
, table1.time
, table2.mg_amount + table3.mg_amount amount
, table2.mg_key + table.mg_key
FROM table
LEFT
JOIN table2
, table3
ON table1.mg_key = key
AND key = amount


It doesn't work, so Im probably doing something wrong?

Answer

http://sqlfiddle.com/#!9/65dca/1/0

SELECT   
table1.mg_key, table1.mg_name, table1.time,
IFNULL(table2.mg_amount,0) + IFNULL(table3.mg_amount,0) as amount
FROM table1
LEFT JOIN table2 ON table1.mg_key = table2.mg_key
LEFT JOIN table3 ON table1.mg_key = table3.mg_key;

If this does not answer your question, please create a SQL Fiddle to help us better understand.