按第一表的结果分组的第二表的总和

时间:2009-01-04 20:24:05

标签: mysql

使用MySQL语法,如何编写查询以返回以下内容(我包括两个表描述及它们之间的关系):

TABLE_A (ID, DATE, TABLE_C_ID)
TABLE_B (ID, AMOUNT, TABLE_A_ID)
TABLE_C (ID)

我想返回以下内容,但具有指定的限制:

SELECT 
    TABLE_A.ID, 
    TABLE_A.DATE 
    (SUM TABLE_B.AMOUNT 
         FROM TABLE_B 
         WHERE TABLE_B.ID = TABLE_A.ID) 
    FROM TABLE_A, TABLE_B 
    WHERE TABLE_A.TABLE_C_ID = 123

提前致谢。

1 个答案:

答案 0 :(得分:2)

这样做有什么问题?:

SELECT 
    TABLE_A.ID, 
    TABLE_A.DATE,
    SUM( TABLE_B.AMOUNT ) AS AMOUNT

FROM TABLE_A

INNER JOIN TABLE_B 
ON TABLE_B.ID = TABLE_A.ID

WHERE TABLE_A.TABLE_C_ID = 123

GROUP BY TABLE_A.ID, 
    TABLE_A.DATE