Jhay
Jhay

Reputation: 33

How to get the closest row to the current date in my table?

I would like to pull out the table from the database where the current day lands when the user visits the page.

Table Sample:

---+----------+-----------
ID |   from   |    to
---+----------+-----------
1  |2015-07-01|2015-07-14
---+----------+-----------
2  |2015-07-15|2015-07-31
---+----------+-----------
3  |2015-08-01|2015-08-20

OUTPUT:

if the date is 2015-07-10 the output should be ID 1

if the date is 2015-08-02 the output should be ID 3

Upvotes: 2

Views: 43

Answers (1)

Kristoffer Svanmark
Kristoffer Svanmark

Reputation: 778

If I understand your question right, what you want to do is to select the row where today's date is between "from" and "to"?

If that's the case you should do something like this:

SELECT id
FROM your_table_name 
WHERE CURDATE() >= `from`
    AND CURDATE() <= `to`

Or if you like:

SELECT id
FROM your_table_name
WHERE CURDATE() BETWEEN `from` AND `to`

Both queries will return one or many rows where today's date is in between "from" and "to".

Upvotes: 1

Related Questions