我有一个看起来像这样的表:
code int, primary key
reservation_code int,
indate date,
outdate date,
slot int,
num int,
该数据库的设计有点奇怪,它的工作方式是该表保留每个插槽预订的日期,num 用于跟踪连续预订,我认为这是遗留原因。
我正在尝试提出一个查询来检查数据库中的先前预订。我这样做的想法:
对于给定的槽号,检查是否有一组具有相同 reservation_code 的行,在该组中具有最小 num 值的行上的日期日期小于或等于给定日期,并且该行上的日期为过期日期最大 num 值高于相同的给定日期。
我在 SQL 中最接近的方法:
编辑:在 Barmar 的帮助下
SELECT b.reservation_code
FROM bookings b
JOIN (SELECT reservation_code, MIN(num) minnum
FROM bookings
WHERE slot = "given_slot"
AND indate <= "given_date"
GROUP BY reservation_code) min
ON minnum = num and b.reservation_code = min.reservation_code
JOIN (SELECT reservation_code, MAX(num) maxnum
FROM bookings
WHERE slot = "given_slot"
AND outdate > "given_date"
GROUP BY reservation_code) max
ON maxnum = num and b.reservation_code = max.reservation_code
WHERE slot="given_slot"
AND indate <= "given_date"
AND outdate > "given_date"
GROUP BY b.reservation_code
将 GROUP BY 添加到两个子查询使其适用于大多数情况,但第二次检查仍然返回错误答案。
以下是一些示例行和查询,试图使问题更清晰:
示例行:
code reservation_code indate outdate slot num
1 1 01/01/13 03/01/13 1 0
2 1 03/01/13 05/01/13 1 1
3 1 05/01/13 10/01/13 1 2
4 2 04/01/13 15/01/13 2 0
5 2 15/01/13 19/01/13 2 1
6 3 11/01/13 13/01/13 1 0
7 4 15/01/13 16/01/13 3 0
8 5 01/01/13 15/01/13 3 0
9 5 15/01/13 25/01/13 4 1
样品检查:
slot 2, date 21/02/13, should return not booked.
slot 2, date 16/01/13, should return booked
slot 1, date 14/01/13, should return not booked
slot 1, date 12/01/13, should return booked
slot 1, date 10/01/13, should return not booked
slot 3, date 02/01/13, should return booked
slot 4, date 15/01/13, should return booked
slot 4, date 25/01/13, should return not booked