iceDice
iceDice

Reputation: 79

Mysql - check if date is in some range

Assume that we have a table like this:

(ID, StartDate, EndDate, SubjectID)
(1, '2018-01-01', '2018-02-01', '1')
(2, '2018-03-01', '2018-04-01', '1')
(n, '2018-06-01', '2018-06-15', '1')

For the specified date (for example '2018-04-04'), i want to check if this date is in any of existing ranges for that subject. How to do this in Mysql? Problem is that number of ranges is variable per subject (we can have 1 to n rows (ranges) per subject).

Upvotes: 0

Views: 279

Answers (2)

Shalvin
Shalvin

Reputation: 178

You can very easily get the required output using the "Greater Than Equal To" and the "Less Than Equal To" filter in mysql. Simply place the query as

Select SubjectID From your_table
Where StartDate <= '2018-04-04' 
AND EndDate >= '2018-04-04';

It should do the trick. Cheers.

Upvotes: 2

Pritam Banerjee
Pritam Banerjee

Reputation: 18923

You can simply do this:

SELECT DISTINCT SubjectID FROM table_name WHERE StartDate < '2018-04-04' 
  AND EndDate > '2018-04-04';

Upvotes: 1

Related Questions