开发者

What is sql structure max amount for mySQL?

TABLE_A has field ( id, name )

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

2   |     Y

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

TABLE_B has field ( id , table_a_id , amount )

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

2   |    1                |  5

3   |    2                |  5 

4   |    1   开发者_JAVA百科             |  5

5   |    3                |  20

6   |    1                |  10

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

I want display result this . Please help about query structure for mySQL .Thank you .

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

Z           |    20

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


This is what you need:

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

The LEFT JOIN will ensure that if you have a W in table A with no lines in table B, W will be displayed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜