简体   繁体   中英

mysql join and sum problems

Im having some trouble with this.

Here's an example of my tables.

Booking

id zone_id name excursion_id
1  2               1
2  1               1
3  2               1

The table where I have the quantities booking_price

id_booking id_price quantity
1              1       2
1              2       3
2              1       1
2              2       0
3              1       2
3              2       3

Here the zone table

Zone
id  Name
1    a
2    b
3    c

So I want to have a table like that

Zone_id Quantity
1          1  
2          10
3          0

The problem is when im joining tables and filtering by excursion_id im not getting ALL the zones.

I want to know how many people goes in each zone.

I think better way of doing it is

select z.id, coalesce(sum(bp.quantity),0) as quantity
from Booking b 
right join Zone z on z.id = b.zone_id AND b.excursion_id = 1
left join booking_price bp on bp.id_booking = b.id
group by z.id

demo http://sqlfiddle.com/#!2/771f5/13

You could use a query like:

   SELECT zone.id as zone_id,
          sum(quantity) as Quantity
     FROM zone
LEFT JOIN Booking on Booking.zone_id = zone.id
LEFT JOIN Excursion on Excursion.id_booking = Booking.id
 GROUP BY zone.id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM