[英]Return only the higher ID from a MySQL query
I have 2 tables: 我有2张桌子:
___Rooms ___Rooms
|--------|------------|
| ROO_Id | ROO_Number |
|--------|------------|
| 22 | 101 |
| 23 | 102 |
| 24 | 201 |
|--------|------------|
___Bookings ___Bookings
|--------|------------|------------|------------|-------------------|
| 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 |
|--------|------------|------------|------------|-------------------|
My goal is to have the following report: 我的目标是得到以下报告:
The date of the report is today :
2018-07-18
.报告日期为:
2018-07-18
。
|------------|----------------|-------------------|
| ROO_Number | BOO_LiveStatus | BOO_ArrivalStatus |
|------------|----------------|-------------------|
| 101 | in-house | checkin |
| 102 | none | no |
| 201 | none | no |
|------------|----------------|-------------------|
I put a SQLFidde here : http://sqlfiddle.com/#!9/bb6a30/4 我在这里放了一个SQLFidde: http ://sqlfiddle.com/#!9 / bb6a30 / 4
Actually, I'm very near but I have a little problem. 实际上,我很近,但我有一点问题。
I need to have only one row per room. 我需要每个房间只有一排。 For room #102, I have two successive bookings and my query returns me two rows for it whereas it should return me
the booking with the higher id (BOO_Id)
. 对于#102房间,我有两个连续的预订,我的查询返回两行,而它应该返回我
the booking with the higher id (BOO_Id)
。
My last try was this one: 我的最后一次尝试就是这个:
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
Could you please help me please ? 你能帮帮我吗?
Thanks a lot. 非常感谢。
YOu should add an inner join on the max(BOO_DateCI) group by BOO_RoomId 你应该通过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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.