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?
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'
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 expressionexpr2
to the date or datetime expressionexpr1
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With