Skip to content
Advertisement

mysql query between days and calculate days between dates

i need to get the id and days count between days.

INSERT INTO Events
    (`ID`, `START`, `END`)
VALUES
    (2313, '2019-07-29', '2019-08-10'),
    (41, '2019-06-22', '2019-07-01'),
    (2540, '2019-06-22', '2019-07-02'),
    (2234, '2019-06-28', '2019-07-12'),
    (2634, '2019-06-30', '2019-07-04'),
    (53, '2019-06-30', '2019-07-02'),
    (1869, '2019-06-30', '2019-07-15'),
    (2132, '2019-07-30', '2019-08-10')
;

my query is

SELECT `ID`
  FROM Events 
 WHERE `START` BETWEEN '2019-07-01' AND '2019-07-31' 
   AND `END` BETWEEN '2019-07-01' AND '2019-07-31';

i need output as

2313 - 3
41 - 1
2540 - 2
2234 - 12
.....

please help me.

Advertisement

Answer

GREATEST returns max value from list, LEAST – min

select ID, 
       DATEDIFF(LEAST(`END`,'2019-07-31'), GREATEST(`START`, '2019-07-01')) + 1
from events
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement