我有以下表结构:
roominfo
表
+---------+----------------+---------------+ | Room_id | room_type_name | maximum_rooms | +---------+----------------+---------------+ | 1 | A | 16 | | 2 | B | 14 | | 3 | C | 7 | | 4 | D | 2 | | 5 | E | 2 | +---------+----------------+---------------+
bookedtable
存储该日期内预订的所有客房:
+------------+--------------+---------------+----------------+---------+ | room_bk_id | checkin_date | checkout_date | maxroomsbooked | room_id | +------------+--------------+---------------+----------------+---------+ | 1 | 2014-01-28 | 2014-01-29 | 8 | 1 | | 2 | 2014-01-29 | 2014-01-30 | 2 | 4 | | 3 | 2014-01-28 | 2014-01-29 | 4 | 1 | +------------+--------------+---------------+----------------+---------+
bookingprogress
表以避免竞争条件(它阻止到期时间)我将最长到期时间设置为距离当前时间15分钟
+------------+----------------+-----------------+----------------+---------+---------------+---------------------+ | room_pg_id | checkinpg_date | checkoutpg_date | maxroomsbooked | room_id | sessionid | ExpireTime | +------------+----------------+-----------------+----------------+---------+---------------+---------------------+ | 1 | 2014-01-28 | 2014-01-29 | 2 | 1 | AdsddsA23asd | 2014-01-28 00:15:00 | | 2 | 2014-01-29 | 2014-01-30 | 2 | 5 | AdsQWerasdwe | 2014-01-28 00:18:00 | | 3 | 2014-01-28 | 2014-01-29 | 1 | 2 | BdrtQWerasdwe | 2014-01-28 00:20:00 | +------------+----------------+-----------------+----------------+---------+---------------+---------------------+
工作流程为:
执行的查询是(可能是小错误 - 在这里我概述了我所做的事情 - 根据这个修改我的查询)
SELECT tbook.*,
SUM(tbook.maxroomsbooked + tprogress.maxroomsbooked) AS bookedrooms
FROM bookedtable AS tbook
JOIN bookingprogress AS tprogress USING (Room_id)
JOIN roominfo AS troomtype USING (Room_id)
WHERE tbook.checkout_date > '2014-01-28'
AND tprogress.checkoutpg_date > '2014-01-28'
AND tprogress.ExpireTime < '2014-01-27 00:10:00'
AND tprogress.room_id = 1
GROUP BY Room_id
从上表中我试图获得可预订的房间。但我没有得到预期的结果。
在sqlfiddle上查看。
你能帮我解决一下吗?
答案 0 :(得分:0)
一种方法是使用NOT EXISTS
subqueries。例如,如果用户有兴趣预订'2014-02-01'
至'2014-02-07'
:
SELECT *
FROM roominfo r
WHERE NOT EXISTS (
SELECT *
FROM bookedtable b
WHERE b.room_id = r.room_id
AND NOT (
b.checkin_date < '2014-02-07'
AND b.checkout_date > '2014-02-01'
)
LIMIT 1
)
AND NOT EXISTS (
SELECT *
FROM bookingprogress p
WHERE p.room_id = r.room_id
AND p.ExpireTime > CURRENT_TIME
AND NOT (
p.checkinpg_date < '2014-02-07'
AND p.checkoutpg_date > '2014-02-01'
)
LIMIT 1
)