我想在 CodeIgniter 中选择 dateStart 和 dateEnd 之间的空闲房间。
我有 2 张桌子 - 房间和预订。
我当前的型号代码:
$this->db->select('rooms.*');
$this->db->join('reservations', 'rooms.ID = reservations.RoomID', 'left outer');
$this->db->where('rooms.Size >=', $PeopleNumber);
$this->db->where('reservations.DateStart <=', $DateEnd);
$this->db->where('reservations.DateEnd >=', $DateStart);
$this->db->group_by('rooms.Size');
$query = $this->db->get('rooms');
我已经检查过这个问题:MySQL Looking for free rooms in booking system
但我不知道如何在 CodeIgniter 中进行多重选择。
我的 SQL 小提琴:http://sqlfiddle.com/#!9/c1f95/8
好的,我解决了这个问题:
$this->db->where('`ID` NOT IN (SELECT `RoomID` FROM `reservations` WHERE `DateStart` < "' .$DateEnd. '" AND `DateEnd` > "' .$DateStart. '")', NULL, FALSE);
不要运行
NOT IN (subquery)
,而是使用 LEFT JOIN 来隔离未预订的房间或具有非重叠预订的房间。 请注意,我确实测试了渲染的 SQL 输出,但我没有费心设置数据库来测试结果集的准确性——这部分是推测的。
// sample variable values
$DateEnd = '2024-05-01';
$DateStart = '2024-04-01';
$PeopleNumber = 2;
$this->db
->select('rooms.*')
->join(
'reservations',
'rooms.ID = reservations.RoomID
AND reservations.DateStart <= ' . $this->db->escape($DateEnd) . '
AND reservations.DateEnd >= ' . $this->db->escape($DateStart),
'left'
)
->group_start()
->or_where([
'reservations.ID' => null,
'reservations.DateStart >' => $DateEnd,
'reservations.DateEnd <' => $DateStart,
])
->group_end()
->get_where('rooms', ['rooms.Size >=' => $PeopleNumber])
->result();
渲染的 SQL(带有我的示例数据和添加的间距):
SELECT `rooms`.*
FROM `rooms`
LEFT JOIN `reservations` ON `rooms`.`ID` = `reservations`.`RoomID`
AND `reservations`.`DateStart` <= '2024-05-01'
AND `reservations`.`DateEnd` >= '2024-04-01'
WHERE (
`reservations`.`ID` IS NULL
OR `reservations`.`DateStart` > '2024-05-01'
OR `reservations`.`DateEnd` < '2024-04-01'
)
AND `rooms`.`Size` >= 2