[英]SQL where time in timestamp
I have records like: 我有类似的记录:
2017-07-24 16:59:32
2017-07-24 17:53:38
2017-07-24 22:26:08
2017-07-24 23:04:54
2017-07-25 08:33:43
2017-07-25 10:06:47
And I want to write an sql query which compares only the time part of timestamp, as example: 我想编写一个sql查询,仅比较时间戳的时间部分,例如:
SELECT * FROM table WHERE date BETWEEN '17:30:00' and '22:30:00'
Check only the time and ignore the date. 仅检查时间而忽略日期。 Is it possible to do so?
有可能这样做吗?
I'm using MySQL 我正在使用MySQL
SELECT * FROM table WHERE hour('date') = 9;
Takes full hour, as I sometimes need to take only half of an hour. 需要一个小时,因为有时我只需要半个小时。
This should work: 这应该工作:
SELECT * FROM table
WHERE
(HOUR(date) BETWEEN 18 AND 21) OR
(HOUR(date) = 17 AND MINUTE(date)>=30) OR
(HOUR(date) = 22 AND MINUTE(date)<=30);
Or another approach would be to convert to DATE
, add the hours and minutes and then use between. 或另一种方法是将其转换为
DATE
,添加小时和分钟,然后在两者之间使用。
SELECT * FROM table
WHERE date BETWEEN
ADDDATE(ADDDATE(DATE(date), INTERVAL 17 HOUR), INTERVAL 30 MINUTE)
AND
ADDDATE(ADDDATE(DATE(date), INTERVAL 22 HOUR), INTERVAL 30 MINUTE);
You can convert the DATETIME
to a time and use that in the comparison. 您可以将
DATETIME
转换为DATETIME
,并在比较中使用它。
Given the sample code: 给定示例代码:
CREATE TABLE Table1
(
Column1 VARCHAR(50),
Column2 VARCHAR(50),
Timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO
Table1
(Column1, Column2, Timestamp)
VALUES
('Valid', 'Time', '2017-01-01 17:43:01'),
('Invalid', 'Time', '2017-01-01 16:00:43');
You could query it like the following: 您可以如下查询:
SELECT
*,
DATE_FORMAT(`timestamp`, '%H:%i:%s') AS Time
FROM
Table1
WHERE
DATE_FORMAT(`timestamp`, '%H:%i:%s') BETWEEN '17:30:00' AND '22:30:00';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.