来自2个表的MySQL SUM值和JOIN
问题描述:
我有两个表,table2
和table3
都可能包含table1中key
的金额.
I have two tables and both table2
and table3
may contain an amount for the key
from table1.
我想总结这些值并将它们表示为amount
.
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?
答
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;
如果这不能回答您的问题,请创建 SQL小提琴以帮助我们更好地理解.
If this does not answer your question, please create a SQL Fiddle to help us better understand.