The matched days count between two dates ranges

E-housma Mardini :

I have two dates for reservation for example I have reservation starts at 2020-03-01 and ends at 2020-04-10.

So when I make select query to know how many days this room has been reserved in the 4th month i want to get count of days 10

Is there anyway to do it in Mysql.

SELECT from_date , to_date  
FROM reservations 
WHERE room_id = ? 
AND from_date >= "2020-04-01" AND to_date >= "2020-04-30"
Gordon Linoff :

You can use datediff() andleast()andgreatest()`. I think the logic you want is:

SELECT DATEDIFF(LEAST(to_date, '2020-04-30'),
                GREATEST(from_date, '2020-04-01')
               ) + 1  
FROM reservations 
WHERE room_id = ? AND
      to_date >= '2020-04-01' AND
      from_date <= '2020-04-30';

Note that the date logic in the WHERE clause has been modified. This is the correct logic for determining if two time periods overlap. The first ends after the second starts; the first starts before the second ends.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=17870&siteId=1