通过mysql查询找到时间介于from和to之间的时间

8fsztsew  于 2021-06-24  发布在  Mysql
关注(0)|答案(3)|浏览(369)

我的table上有一个来回的时间。如果用户选择12:30 am或11:00 pm,则其中一条记录是从\u时间:19:00:00到\u时间:01:30:00。我如何正确地找到它是从\到\之间的时间。
我尝试的mysql查询:

SELECT * FROM `table` WHERE  '19:00:00' >= from_time  and '19:00:00' <= to_time

不起作用。

goqiplq2

goqiplq21#

对于超过午夜的时间,您可以添加24小时,然后进行测试。例如

drop table if exists t;
create table t(from_time time, to_time time);
insert into t values
('18:00:00','20:00:00'),
('18:00:00','01:00:00'),
('16:00:00','18:00:00');

select from_time,to_time,
         case when  '19:00:00' between 
                from_time and
         if(to_time < from_time, 
         addtime(to_time,'24:00:00'),
          to_time) 
          then 'true'
         else 'false'
         end as truefalse
from t;
+-----------+----------+-----------+
| from_time | to_time  | truefalse |
+-----------+----------+-----------+
| 18:00:00  | 20:00:00 | true      |
| 18:00:00  | 01:00:00 | true      |
| 16:00:00  | 18:00:00 | false     |
+-----------+----------+-----------+
3 rows in set (0.00 sec)
6ljaweal

6ljaweal2#

您的问题不会显示所选时间的来源。它是在一列中,是用户在sql中设置的还是通过代码发送的?
如果在sql中设置了时间,则方法如下:

SET @mytime := '19:00:00';
SELECT * FROM `table` WHERE CAST(@mytime AS TIME) BETWEEN from_time AND to_time;

其中@mytime是用户设置的变量,假设from\u time和to\u time是时间格式。
我的上述测试表如下:

CREATE TABLE `timetest` (
  `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `from_time` time DEFAULT NULL,
  `to_time` time DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

试验数据如下:

INSERT INTO `timetest` (`id`, `from_time`, `to_time`) VALUES
(1, '09:00:00', '11:00:00'),
(2, '06:30:00', '14:00:00'),
(3, '14:29:10', '16:12:18'),
(4, '09:11:17', '23:00:01'),
(5, '18:00:00', '23:59:59'),
(6, '01:12:00', '11:59:44');
8aqjt8rx

8aqjt8rx3#

您使用了值而不是列名
您可以使用如下查询。您可以根据需要更改价值。
先根据您的需要更改时间值。
第一个选项 Where ```
SELECT * FROM table WHERE from_time >= '00:00:00' and to_time <= '23:59:59'

第二种选择是 `between` ```
SELECT * FROM `table` WHERE  from_time between '00:00:00'  and '23:59:59'

相关问题