在我的“预订”表中,每个预订都有人数和一个“ event_time”,这是三个可预订的时段之一。
在我的查询中,我试图返回每个餐厅和时段(event_time编号)还剩下多少个免费座位
我选择了餐厅,并进行了内部联接以包括预订表,但是我需要从内部联接的 inside 餐馆表中访问“ number_of_seats_max”列。
这里是fiddle。
表格:
CREATE TABLE `restaurants` (
`id` int(10) UNSIGNED NOT NULL,
`title` text COLLATE utf8mb4_unicode_ci,
`number_of_seats_max` int(11) DEFAULT NULL
);
CREATE TABLE `bookings` (
`id` int(10) UNSIGNED NOT NULL,
`event_date` timestamp NULL DEFAULT NULL,
`event_time` int(11) NOT NULL,
`number_of_persons` int(11) NOT NULL,
`restaurant_id` int(11) NOT NULL
);
以下查询有效,但是在这种情况下,我使用硬编码“ 80 ”代替了最大席位栏(r.number_of_seats_max
。那就是我需要使用的列。如果改用r.number_of_seats_max
,则会收到错误“ unknown column
”。
SELECT r.title, r.number_of_seats_max, innerquery.free_seats_left,
innerquery.num_persons_booked
FROM restaurants r
INNER JOIN(
select
restaurant_id,
SUM(number_of_persons) as num_persons_booked,
(80 - SUM(number_of_persons)) AS free_seats_left // <-- 80 is hard coded
from bookings
WHERE event_date = '2019-07-18'
group by event_time,restaurant_id
ORDER BY free_seats_left DESC
) as innerquery
ON innerquery.restaurant_id = r.id;
我该如何解决?
答案 0 :(得分:1)
在主查询而不是子查询中进行减法。
SELECT r.title, innerquery.event_time, r.number_of_seats_max,
r.number_of_seats_max - innerquery.num_persons_booked AS free_seats_left,
innerquery.num_persons_booked
FROM restaurants r
INNER JOIN(
select
restaurant_id,
event_time,
SUM(number_of_persons) as num_persons_booked
from bookings
WHERE event_date = '2019-07-18'
group by event_time,restaurant_id
) as innerquery
ON innerquery.restaurant_id = r.id
ORDER BY free_seats_left DESC
我在子查询和主查询的event_time
列表中都添加了SELECT
,因此您可以显示每个时隙的可用席位。