Hello. There is such a database: http://sqlfiddle.com/#!9/9554b . The first table is responsible for displaying hotel rooms that exist, the second for existing hotel bookings. I tried to visualize it:
For this order of arrangement / distribution of numbers meets the sql code. He takes new dates of arrival and departure, compares them with the main table and checks the available number for these dates. The first available free number he assigns to new armor. Everything is logical. From here and it follows such a "chaotic" distribution of numbers. Here, actually, itself select request for issue of number.
SET @start = '2016-12-12'; -- Новая дата заезда SET @end = '2016-12-20'; -- Новая дата выезда SELECT a.nomer FROM allnomer a LEFT JOIN main m ON a.nomer = m.numbernomer AND DATEDIFF(m.datestart, @end) * DATEDIFF(m.dateend, @start) <= 0 WHERE a.type = 'lux' AND m.numbernomer IS NULL LIMIT 1 But I have one problem. In fact, no one will live in the hotel on the 12th, 13th, 14th ... 20th day. These are free days. They were formed due to the distribution of dates by my script. But if the 11th number comes with a reservation for dates from 12 to 20, then the script will reject it (return null), because the check-in / check-out dates overlap. And this is quite expected, but I would like to solve this problem. If you redistribute the reservation, then everything will fall into place, and the number from 12 to 20 will open.
I did not touch the existing armor, I moved only future ones. I would like to know how real this idea is with redistribution / defragmentation, and how to implement it (maybe there was already something similar, or is there such a sql query for my case)?