子查询还是不写这个查询?

时间:2012-01-12 16:35:28

标签: sql

我的SQL查询:

select 
    *, 
    (select sum(Amount) as TotalAmount 
     from Payment 
     where Customer.Id = Payment.CustomerId) 
from Customer 

结果:

Id - CustomerName - CustomerPhoneNumber - TotalAmount
1  - TestUser     - TestLastName        - 3000   
2  - TestUser2    - TestLastName2       - 2500 

这正如我所料。但有没有更好的方法来获得相同的结果?

2 个答案:

答案 0 :(得分:1)

如果是MySQL,那么你可以这样做......

SELECT
  Customer.*,
  SUM(Payment.Amount) AS TotalAmount
FROM
  Customer
LEFT JOIN
  Payment
    ON Payment.CustomerId = Customer.Id
GROUP BY
  Customer.id

在其他各种SQL中,您需要GROUP BY所有选定但不是聚合的内容。

SELECT
  Customer.Id,
  Customer.Name,
  Customer.PhoneNumber,
  SUM(Payment.Amount) AS TotalAmount
FROM
  Customer
LEFT JOIN
  Payment
    ON Payment.CustomerId = Customer.Id
GROUP BY
  Customer.Id,
  Customer.Name,
  Customer.PhoneNumber

答案 1 :(得分:1)

您可以使用LEFT JOINGROUP BY重写它:

select 
a.*, sum(b.Amount) as TotalAmount    
from Customer a
left join Payment on (a.Id = b.CustomerId)
GROUP BY a.Id -- for mysql only, for other RDMS you have to list all Customer fields

 select 
a.*, b.TotalAmount    
from Customer a
left join 
(SELECT CustomerId, SUM(Amount) as TotalAmount 
 FROM Payment GROUP BY CustomerId)b  ON (b.CustomerId = a.Id)