我需要进行非常复杂的搜索
上下文:我有3个表:rooms,reservation和room_reservation。第一个包含酒店房间的所有信息,第二个包含所有预订的信息,第三个是因为预订有多个房间。
我需要知道在特定日期有哪些房间可用,我真的很接近,我需要如果至少有一个数据与搜索条件不符,那么相关房间就不会显示。
这是我的疑问:
SELECT DISTINCT hab.* FROM habitacion hab
LEFT OUTER JOIN habitacion_reserva habr ON habr.id_habitacion = hab.id
LEFT OUTER JOIN reserva res ON res.id = habr.id_reserva
WHERE hab.tipo = 1
AND (((( '2018-06-10' not between res.fecha_ingreso and res.fecha_salida) AND ( '2018-06-17' not between res.fecha_ingreso and res.fecha_salida))
OR (res.fecha_ingreso is null OR res.fecha_salida is null)) OR ((( '2018-06-09' between res.fecha_ingreso and res.fecha_salida) OR ( '2018-06-17' between res.fecha_ingreso and res.fecha_salida)) AND res.estado = 4))
理论上,查询有效,但当我有很多预订时,查询只会返回所有房间。
答案 0 :(得分:1)
尝试这样的事情(简化)
Select * FROM rooms
LEFT JOIN room_reservation ON (rooms.id = rooms_reservation.id)
LEFT JOIN reservations ON (rooms_reservation.id = reservation.id)
reservation
WHERE 1=1
...
AND whateverfield = 1
....
AND ('2018-06-09' NOT BETWEEN reservation.start AND reservation.end)
AND ('2018-06-17' NOT BETWEEN reservation.start AND reservation.end)
GROUP BY rooms