我有2张桌子:
___房间
|--------|------------|
| ROO_Id | ROO_Number |
|--------|------------|
| 22 | 101 |
| 23 | 102 |
| 24 | 201 |
|--------|------------|
___预订
|--------|------------|------------|------------|-------------------|
| BOO_Id | BOO_RoomId | BOO_DateCI | BOO_DateCO | BOO_ArrivalStatus |
|--------|------------|------------|------------|-------------------|
| 34 | 22 | 2018-07-17 | 2018-07-20 | checkin |
| 35 | 23 | 2018-07-17 | 2018-07-18 | checkout |
| 36 | 24 | 2018-07-19 | 2018-07-21 | none |
| 37 | 23 | 2018-07-18 | 2018-07-21 | none |
|--------|------------|------------|------------|-------------------|
我的目标是提供以下报告:
报告日期为今天
2018-07-18
。
|------------|----------------|-------------------|
| ROO_Number | BOO_LiveStatus | BOO_ArrivalStatus |
|------------|----------------|-------------------|
| 101 | in-house | checkin |
| 102 | none | no |
| 201 | none | no |
|------------|----------------|-------------------|
我在这里放了一个SQLFidde: http://sqlfiddle.com/#!9/bb6a30/4
实际上,我距离很近,但是我有一个小问题。
每个房间只需要排一行。对于102号房,我有两次连续的预订,查询返回两行,而它应该返回the booking with the higher id (BOO_Id)
。
我最后一次尝试是这样:
SELECT
ROO_Id,
IF(BOO_DateCI <= '2018-07-18' AND BOO_DateCO >= '2018-07-18', "in-house", "no")
AS BOO_LiveStatus,
IFNULL(BOO_ArrivalStatus, "0")
AS BOO_ArrivalStatus,
BOO_Id,
FROM ___Rooms
LEFT JOIN ___Bookings
ON ___Rooms.ROO_id = ___Bookings.BOO_RoomId
AND '2018-07-18' BETWEEN ___Bookings.BOO_DateCI AND ___Bookings.BOO_DateCO
WHERE ROO_Status != 'inactive'
ORDER BY
ROO_Number
能请你帮我吗?
非常感谢。
答案 0 :(得分:1)
您应该通过BOO_RoomId在max(BOO_DateCI)组上添加内部联接
SELECT
ROO_Id,
IF(BOO_DateCI <= '2018-07-18' AND BOO_DateCO >= '2018-07-18', "in-house", "no")
AS BOO_LiveStatus,
IFNULL(BOO_ArrivalStatus, "0")
AS BOO_ArrivalStatus,
BOO_Id
FROM ___Rooms
inner join (
select BOO_RoomId,max(BOO_DateCI) max_BOO_DateCI
from ___Bookings
group by BOO_RoomId
) t on t.BOO_RoomId = ___Rooms.ROO_id
LEFT JOIN ___Bookings
ON ___Rooms.ROO_id = ___Bookings.BOO_RoomId
AND '2018-07-18' BETWEEN ___Bookings.BOO_DateCI AND ___Bookings.BOO_DateCO
AND t.max_BOO_DateCI= ___Bookings.BOO_DateCI
ORDER BY
ROO_Number