问题
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?
回答1:
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'
回答2:
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'
回答3:
Here's a clean version that doesn't require string operations or conversion to to UTC timestamps across time zones.
DATE_ADD(date, INTERVAL time HOUR_SECOND)
回答4:
All you have to do is to convert it into unix timestamp and make appropriate selections. For this you have to use mysql functions like *unix_timestamp().* and *date_format*
Suppose you want to select rows where timestamp > 1328725800, the following sql statement would do the task.
select unix_timestamp(d)+3600*date_format(t,'%h)+60*date_format(t,'%i')+date_format(t,'%S') as timestamp from table where timestamp>1328725800
回答5:
Actually it should be:
SELECT * FROM `mytable` WHERE CONCAT(`d`,' ',`t`) > '2012-02-01 15:00:00'
If you want to take seconds into account, you need to add the two digits to the end ;)
来源:https://stackoverflow.com/questions/9187437/how-to-combine-date-and-time-from-different-mysql-columns-to-compare-to-a-full-d