我正在运行此查询
SELECT events.*, venues.*,
SUM(events.eventCAPACITY) AS capacity,
SUM(CASE WHEN bookings.bookingAMOUNT is NULL THEN 0 ELSE bookings.bookingAMOUNT END) AS booked,
SUM(events.eventCAPACITY) - SUM(CASE WHEN bookings.bookingAMOUNT is NULL THEN 0 ELSE bookings.bookingAMOUNT END) AS available
FROM events
LEFT JOIN bookings ON events.eventID = bookings.bookingEVENT
LEFT JOIN venues ON venues.venueID = events.eventVENUE
WHERE events.eventDATE >= CURDATE()
GROUP BY events.eventID
ORDER BY events.eventDATE, events.eventTIME ASC
一切顺利。除非达到了event.eventCAPACITY(例如20)(通过另一个表),否则它不为零,而是再次给出在events.eventCAPACITY中设置的数量(20)。
我究竟做错了什么?
编辑
这是我从运行查询中得到的结果。
eventID | eventDATUM | eventTIJDSTIP | eventVENUE | eventCAPACITY | 地点编号 | 地点NAME | 容量 | 已预订 | 有空 |
---|---|---|---|---|---|---|---|---|---|
1个 | 2021-01-24 | 12:00:00 | 1个 | 15 | 1个 | 地点1 | 15 | 0 | 15 |
2 | 2021-01-24 | 11:00:00 | 2 | 15 | 2 | 地点2 | 15 | 0 | 15 |
3 | 2021-01-13 | 09:00:00 | 1个 | 15 | 1个 | 地点1 | 30 | 15 | 15 |
第三行的预期结果应为容量15而不是30,可用容量应为0而不是15。
这些是桌子。
餐桌预订
bookingID | bookingFIRSTNAME | bookingLASTNAME | bookingEMAIL | bookingEVENT | bookingAMOUNT |
---|---|---|---|---|---|
25 | 约翰 | 史密斯 | [email protected] | 3 | 10 |
27 | 简 | 史密斯 | [email protected] | 3 | 5 |
表事件
eventID | 活动日期 | eventTIME | eventVENUE | eventCAPACITY |
---|---|---|---|---|
1个 | 2021-01-24 | 12:00:00 | 1个 | 15 |
2 | 2021-01-24 | 11:00:00 | 2 | 15 |
3 | 2021-01-13 | 09:00:00 | 1个 | 15 |
餐桌场地
餐桌场地
地点编号 | 地点NAME |
---|---|
1个 | 地点1 |
2 | 地点2 |
3 | 地点3 |
您不需要SUM()
for events.eventCAPACITY
。该JOIN
之间可以产生重复值(你可以看到,如果你使用GROUP_CONCAT(events.eventCAPACITY
)。
这里的解决方案是SUM()
放手events.eventCAPACITY
SELECT events.*, venues.*,
events.eventCAPACITY AS capacity,
SUM(CASE WHEN bookings.bookingAMOUNT is NULL THEN 0 ELSE bookings.bookingAMOUNT END) AS booked,
events.eventCAPACITY - SUM(CASE WHEN bookings.bookingAMOUNT is NULL THEN 0 ELSE bookings.bookingAMOUNT END) AS available
FROM events
LEFT JOIN bookings ON events.eventID = bookings.bookingEVENT
LEFT JOIN venues ON venues.venueID = events.eventVENUE
WHERE events.eventDATE >= CURDATE()
GROUP BY events.eventID
ORDER BY events.eventDATE, events.eventTIME ASC
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句