来自2个表的MySQL SUM值和JOIN [英] MySQL SUM values from 2 tables and JOIN

查看:85
本文介绍了来自2个表的MySQL SUM值和JOIN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表,table2table3都可能包含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.

这篇关于来自2个表的MySQL SUM值和JOIN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆