我有一个看起来像这样的表:
code int, primary key
reservation_code int,
indate date,
outdate date,
slot int,
num int,
数据库有一些奇怪的设计,它应该工作的方式是这个表保存每个槽预订的日期,num用于跟踪我认为是遗留原因的连续预订。 / p>
我正在尝试提出一个检查数据库中先前预订的查询。我这样做的想法:
对于给定的插槽号,检查是否存在一组具有相同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
答案 0 :(得分:1)
您需要对聚合表
使用JOINSELECT b.reservation_code, count(1)
FROM bookings b
JOIN (SELECT reservation_code, MAX(num) maxnum
FROM bookings
WHERE slot = "given slot"
AND indate <= "given date"
GROUP BY reservation_code) m
ON maxnum = num and b.reservation_code = m.reservation_code
WHERE slot="given slot"
AND indate <= "given date"
GROUP BY b.reservation_code
答案 1 :(得分:0)
经过一夜好眠,我意识到我的问题相当简单,可以通过一个非常简单的查询解决,例如:
SELECT 1
FROM bookings
WHERE slot="given slot"
AND indate <= "given date"
AND outdate > "given date"
我要感谢所有试图帮助我的人,对不起,我浪费了你的时间。