简体   繁体   中英

Sum total of table with two related tables

I'm here with this (I'm sure it is) simple question I can't figure out how to solve.

I have this schema:

图式

With this data:

人桌

水果桌

Cookie表

My expected result is:

For "JOHN NASH":

PERSON_NAME | TOTAL_FRUIT | TOTAL COOKIE
----------------------------------------
JOHN NASH   |       10    |     38  

For "OSCAR WILDE":

PERSON_NAME | TOTAL_FRUIT | TOTAL COOKIE
----------------------------------------
OSCAR WILDE |       28    |      0

Thanks in advance.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM