我有两张 table
表名:月份
我对上面的输出使用下面的查询,但我得到了意想不到的结果。
SELECT a.id
, SUM(a.no_of_units_purchase)
FROM month a
, year b
WHERE a.id=b.id
GROUP
by b.id
请指导我获得预期的结果..
提前致谢..
最佳答案
您应该使用左联接 而不是简单的联接,因为表格月份不能包含给定年份的购买。可行的查询是:
select year.id,
year.no_of_units,
sum(ifnull(month.no_of_units_purchase, 0)) as no_of_units_purchase,
year.no_of_units - sum(ifnull(month.no_of_units_purchase, 0)) as balance_units
from year
left join month on year.id = month.id
group by
year.id,
year.no_of_units
关于php - 如何在mysql中使用inner join或group by从两个表中获取所有余额值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44176386/