在 sql 中需要及时搜索方面的帮助

Need help in search on time in sql

我有一个table这样的

+----+--------+----------+----------+
| id | time_c | time_r   |  some_id |
+----+--------+----------+----------+
|  1 |    900 | 9:00 AM  |        1 |
|  2 |   1000 | 10:00 AM |        2 |
|  3 |   1100 | 11:00 AM |        3 |
|  4 |   1230 | 12:30 PM |        4 |
|  5 |   1300 | 1:00 PM  |        5 |
|  6 |   1410 | 2:10 PM  |        6 |
+----+--------+----------+----------+

现在我想根据时间进行搜索。就像我的用户正在寻找 12:00 下午和 9:00 上午之间,它会告诉他他订购了 4、5、6、1 或 9:00 上午到 12:00 之间下午,它会显示 1、2、3。我正在使用 MariaDB/MySQL。

我该怎么做?请帮忙!

您不应将时间存储为 varchar,而应存储为 "TIME" 格式(如果您使用的是 MySql)。之后,您可以排序为 "ORDER BY time_r DESC".

尝试使用三种不同条件的 UNION ALL 语句

set @time_from = 1200;
set @time_to = 900;

select * 
from some_table
where time_c between @time_from and @time_to

union all

select * 
from some_table
where @time_from > @time_to
  and time_c >= @time_from

union all

select * 
from some_table
where @time_from > @time_to
  and time_c <= @time_to;

演示:http://rextester.com/VMVROK94010

更新

不使用 OR 条件的 UNION 的解决方案恕我直言,可读性较差,并且无法为 WHERE 子句使用索引:

select * 
from some_table
where time_c between @time_from and @time_to
   or @time_from > @time_to
      and (
          time_c <= @time_to
          or
          time_c >= @time_from
      );

演示:http://rextester.com/VFKG60616