多个表之间的总和

时间:2013-02-05 22:40:31

标签: mysql

我有三张桌子:

Services
ID    Name       Price
1     Internet   99.99
2     Phone      49.95
3     TV         159.95

Customers
ID    Name
1     Ryan
2     Simon
3     Jimmy

Customer Services
CustomerID ServiceID
1          1
1          2
2          3

如何查询这些表格以获取客户名称和客户为其所有服务合并支付的总价格?

2 个答案:

答案 0 :(得分:1)

你应该尝试:

SELECT c.name, SUM(s.price) FROM services s
INNER JOIN customer_services sc ON cs.service_id = s.id
INNER JOIN customers c ON c.id = cs.customer_id
GROUP BY c.id

答案 1 :(得分:0)

select 
   c.name, 
   sum(s.price) 
from ((
   customers c
      inner join custserv cs on cs.cid = c.id )
      inner join services s on s.id = cs.sid )
group by 
   c.id