如何SUM查询3个表?

时间:2013-02-20 13:07:58

标签: mysql

A table
--------------------
id bId        txnVolume
1  1(b table) 10.00
2  1          5.00
3  2          7.00
4  3          2.00

B table
--------------------
id cId
1  1(C table)
2  2
3  3

C table
--------------------
id cusId prodId
1  1     1
2  1     2
3  1     1
4  1     2

如果C表是custId 1而prodId 1,我想得到表A上txnVolume的总和?谢谢你的帮助!干杯!

5 个答案:

答案 0 :(得分:1)

Select sum(coalesce(txnVolume,0))
FROM A INNER JOIN B on A.BID = B.Bid
INNER JOIN C on C.ID = B.CID
WHERE C.CustID = 1 and C.ProdID = 1

答案 1 :(得分:1)

尝试以下方法:

select sum(txnVolume) from A
   join B on A.bID = B.id
   join C on C.cID = C.id
  where prodID = 1 and custID = 1

答案 2 :(得分:1)

在sql中你需要加入表格。当表连接时,它们会创建一个大表。然后,您可以在列中添加where子句。

SELECT sum(txnVolume)
FROM A
JOIN B on A.bId = B.id
JOIN C on B.cID = c.id
where c.custid = 1 and c.prodid = 1

答案 3 :(得分:1)

SELECT SUM(a.txnVolume)
FROM c 
  LEFT JOIN b 
    ON c.id=b.cId 
  LEFT JOIN a 
    ON b.id=a.bId 
WHERE c.cusId=1 AND c.prodId=1;

答案 4 :(得分:1)

SELECT  SUM(a.txnVolume) totals
FROM    tableA a
        INNER JOIN tablB b
            ON a.bid = b.id
        INNER JOIN tableC c
            ON b.cid = c.ID
WHERE   c.custID = 1 AND c.prodID = 1