0

我有一个看起来像这样的表:

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
4

2 回答 2

2

您需要对聚合表使用 JOIN

SELECT 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
于 2013-05-31T18:17:43.450 回答
0

经过一夜好眠后,我意识到我的问题相当琐碎,可以通过一个非常简单的查询来解决,例如:

SELECT 1
FROM bookings
WHERE slot="given slot"
AND indate <= "given date"
AND outdate > "given date"

我要感谢所有试图帮助我的人,很抱歉我在这件事上浪费了你的时间。

于 2013-06-02T13:14:20.853 回答