![](/img/trans.png)
[英]MySQL: How do I select two fields from table, and total of amount columns in two related tables?
[英]Sum total of table with two related tables
我在这里(我确定是)这个简单的问题,我不知道如何解决。
我有这个架构:
使用此数据:
我的预期结果是:
对于“ JOHN NASH”:
PERSON_NAME | TOTAL_FRUIT | TOTAL COOKIE
----------------------------------------
JOHN NASH | 10 | 38
对于“ OSCAR WILDE”:
PERSON_NAME | TOTAL_FRUIT | TOTAL COOKIE
----------------------------------------
OSCAR WILDE | 28 | 0
提前致谢。
SELECT name, IFNULL(f.total, 0) AS total_fruit, IFNULL(c.total, 0) AS total_cookie
FROM person AS p
LEFT JOIN (SELECT person_idperson, SUM(cost) AS total
FROM fruit
GROUP BY person_idperson) AS f
ON p.idperson = f.person_idperson
LEFT JOIN (SELECT person_idperson, SUM(cost) AS total
FROM cookie
GROUP BY person_idperson) AS c
ON p.idperson = c.person_idperson
SELECT p.name AS PERSON_NAME,
IFNULL(SUM(f.cost),0) AS TOTAL_FRUIT,
IFNULL(SUM(c.cost),0) AS TOTAL_COOKIE
FROM person AS p
LEFT JOIN fruit as f
ON p.idperson = f.person_idperson
LEFT JOIN cookie as c
ON p.idperson = c.person_idperson
GROUP BY p.idperson
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.