簡體   English   中英

該表與兩個相關表的總和

[英]Sum total of table with two related tables

我在這里(我確定是)這個簡單的問題,我不知道如何解決。

我有這個架構:

圖式

使用此數據:

人桌

水果桌

Cookie表

我的預期結果是:

對於“ 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM