从另一个表添加列,但不影响count()

时间:2011-11-06 22:04:19

标签: mysql sql count

我已经查询了多个JOIN,简单的预订列表

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

输出类似

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

我想添加另一个列,其中包含有关付款的信息,但简单的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

2 个答案:

答案 0 :(得分:1)

以下内容应该有效:

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

但是没有你的数据,这里有一些猜测。

答案 1 :(得分: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