gpt4 book ai didi

mysql - mySQL 的 sql 结构最大数量是多少?

转载 作者:行者123 更新时间:2023-11-29 09:04:01 24 4
gpt4 key购买 nike

TABLE_A 有字段(id、名称)

--------------------------------------
id | name
--------------------------------------
1 | X

2 | Y

3 | Z
--------------------------------------

TABLE_B 有字段( id 、 table_a_id 、 amount )

=====================================
id | table_a_id | amount
=====================================
1 | 1 | 10

2 | 1 | 5

3 | 2 | 5

4 | 1 | 5

5 | 3 | 20

6 | 1 | 10

=======================================

我想要显示结果这个。请帮助了解 mySQL 的查询结构。谢谢。

=====================================
name | amount
=====================================
X | 30

Z | 20

Y | 5
--------------------------------------------------------------

最佳答案

这就是您所需要的:

select max(ta.name) name, coalesce(sum(tb.amount), 0) amount
from Table_A ta
left join Table_B tb
on ta.id = tb.table_a_id
group by ta.id

LEFT JOIN 将确保如果表 A 中有 W,而表 B 中没有行,则将显示 W。

关于mysql - mySQL 的 sql 结构最大数量是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7642960/

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