Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine date and time from different MySQL columns to compare to a full DateTime?

Column d is DATE, column t is time, column v is, for example, INT. Let's say I need all the values recorded after 15:00 of 01 Feb 2012 and on. If I write

SELECT * FROM `mytable` WHERE `d` > '2012-02-01' AND `t` > '15:00'

all the records made before 15:00 at any date are going to be excluded from the result set (as well as all made at 2012-02-01) while I want to see them. It seems it would be easy if there were a single DATETIME column, but there are separate columns for date and time instead in the case of mine.

The best I can see now is something like

SELECT * FROM `mytable` WHERE `d` >= '2012-02-02' OR (`d` = '2012-02-01' AND `t` > '15:00')

Any better ideas? Maybe there is a function for this in MySQL? Isn't there something like

SELECT * FROM `mytable` WHERE DateTime(`d`, `t`) > '2012-02-01 15:00'

possible?

like image 569
Ivan Avatar asked Feb 08 '12 03:02

Ivan


2 Answers

You can use the mysql CONCAT() function to add the two columns together into one, and then compare them like this:

SELECT * FROM `mytable` WHERE CONCAT(`d`,' ',`t`) > '2012-02-01 15:00'
like image 133
Brian Glaz Avatar answered Oct 06 '22 14:10

Brian Glaz


The TIMESTAMP(expr1,expr2) function is explicitly for combining date and time values:

With a single argument, this function returns the date or datetime expression expr as a datetime value. With two arguments, it adds the time expression expr2 to the date or datetime expression expr1 and returns the result as a datetime value.

This resulting usage is just what you predicted:

SELECT * FROM `mytable` WHERE TIMESTAMP(`d`, `t`) > '2012-02-01 15:00'
like image 28
Brad Mace Avatar answered Oct 06 '22 16:10

Brad Mace