2012-01-12 60 views
1

我的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

什麼各種SQL的? – MatBailie 2012-01-12 16:39:04

回答

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

您可以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)