gpt4 book ai didi

mysql - 表与两个相关表的总和

转载 作者:行者123 更新时间:2023-11-30 00:48:52 25 4
gpt4 key购买 nike

我在这里提出这个(我确信是)简单的问题,我不知道如何解决。

我有这个架构:

schema

有了这些数据:

person table

fruit table

cookie table

我的预期结果是:

对于“约翰·纳什”:

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

对于“奥斯卡·王尔德”:

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

关于mysql - 表与两个相关表的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21147796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com