Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql datetime between two columns

I've got two columns (both datetime) startDate and endDate in an events table. I am retrieving the current day using the the date() function of php.

This results in for example 2013-03-12.

Now there are three possibilities of events combined with dates that occur today:

  1. An event starts and also end on this day
  2. An event has started earlier and ends today
  3. An event starts today but ends in the future (>= 2013-03-13)

Now I'd like to break these all into separate queries as I'm not used to work with dates. I started with the first query, but I am already failing on that one. I've tried the following:

SELECT * FROM events WHERE (startDate= '2013-03-12' AND endDate= '2013-03-12')

aswell as:

SELECT * FROM events WHERE NOT (startDate < '2013-03-12' OR endDate > '2013-03-12')

I've tried to use DATE() aswell and to format dates like '2013-03-12%'.

I don't know why it doesn't work while i am sure there is at least 1 event that is taking place on the 12th. Any help is appreciated.

like image 452
Gooey Avatar asked Mar 12 '13 17:03

Gooey


People also ask

How can I get date between two dates in MySQL?

To count the difference between dates in MySQL, use the DATEDIFF(enddate, startdate) function. The difference between startdate and enddate is expressed in days.

How do I select a date range in MySQL?

How to Select rows from a range of dates with MySQL query command. If you need to select rows from a MySQL database' table in a date range, you need to use a command like this: SELECT * FROM table WHERE date_column >= '2014-01-01' AND date_column <= '2015-01-01';

How can I get date between two dates in SQL?

To find the difference between dates, use the DATEDIFF(datepart, startdate, enddate) function. The datepart argument defines the part of the date/datetime in which you'd like to express the difference.

How do I insert date in YYYY-MM-DD format in MySQL?

You can use str_to_date to convert a date string to MySQL's internal date format for inserting.


1 Answers

Try using the MySQL's DATE() function to trim the date columns to the just the date parts:

SELECT * 
FROM events 
WHERE (DATE(startDate) = '2013-03-12' AND DATE(endDate)= '2013-03-12')
like image 179
John Conde Avatar answered Oct 06 '22 02:10

John Conde