2011-11-06 54 views
2

我已經其輸出類似從另一個表添加列,但不影響計數()

reservation_id | customer_id | name | num_of_ordered_services 
    1   | 1909091202 | John |   2 
    2   | 2512541508 | Jane |   3 

我想查詢有多個連接,保留

SELECT reservation.reservation_id, customer.customer_id, customer.name, count(ordered_services.reservation_id) AS num_of_ordered_services 
FROM reservations 
JOIN customers ON reservations.customer_id = customer.customer_id 
LEFT JOIN ordered_services ON reservations.reservation_id = ordered_services.reservation_id 
GROUP BY reservation.reservation_id, customer.customer_id, customer.name 
ORDER BY reservation.reservation_id 

的簡單列表添加另一列有關付款的信息,但簡單的JOIN,LEFT JOIN會干擾現有的count()列。像

SELECT reservation.reservation_id, count(payments.reservation_id) AS num_of_payments 
FROM reservations 
LEFT JOIN payments ON reservations.reservation_id = payments.reservation_id 
GROUP BY reservation.reservation_id 
ORDER BY reservation.reservation_id 

reservation_id | num_of_payments 
    1   |  0 
    2   |  2 

但在一個單一的結果。如何實現這一目標?

PS:num_of_payments不是必需的,我只需要知道是否存在某個預留的支付(1,0)。 謝謝


TBL結構,沒有什麼特別的: 保留

reservation_id | customer_id |  added 
    1   | 1909091202 | 2011-11-04 02:37:28 
    2   | 2512541508 | 2011-11-04 14:27:01 

客戶

customer_id | name | personal information columns ... 
1909091202 | John |  |  | 
2512541508 | Jane |  |  | 
    ...  | ... |  |  | 

支付

payment_id | reservation_id | customer_id | total |  added 
    1  |  2  | 1909091202 | 199 | 2011-11-04 02:37:28 
    2  |  2  | 2512541508 | 50 | 2011-11-04 14:27:01 
+0

不知道你的表結構,這是不能回答的。 –

回答

1

您可以使用子選項作爲附加字段。

SELECT reservation.reservation_id, customer.customer_id, customer.name, 
count(ordered_services.reservation_id) AS num_of_ordered_services, 
(SELECT count(*) FROM payments WHERE reservation.reservation_id=payments.reservation_id) AS num_of_payments 
FROM reservations 
JOIN customers ON reservations.customer_id = customer.customer_id 
LEFT JOIN ordered_services ON reservations.reservation_id = ordered_services.reservation_id 
GROUP BY reservation.reservation_id, customer.customer_id, customer.name 
ORDER BY reservation.reservation_id 
1

Somethi ng如下應該工作:

select 
reservation.reservation_id, 
(case when exists (select * from payments p1 where p1.reservation_id = reservation.reservation_id) then 1 else 0 end) as one_or_many_payments_made 
from reservation 
GROUP BY reservation.reservation_id 
ORDER BY reservation.reservation_id 

但是沒有你的數據,這裏有一些猜測。

+0

謝謝!不過,我不會將這個問題的答案設置爲'接受',而是在我的項目的另一部分中使用這種子查詢。 – babca

相關問題