0

我有这个 mysql 表,上面有php火车的时间表,

Type (INT) | time_start | time_stop
  1        |  09:31:00  | 09:34:00
  1        |  09:43:00  | 09:47:00
  1        |  09:55:00  | 09:58:00
  1        |  10:07:00  | 10:10:00
  1        |  10:33:00  | 10:36:00
  1        |  10:45:00  | 10:47:00
  1        |  10:57:00  | 11:00:00
  1        |  11:12:00  | 11:15:00
  1        |  11:35:00  | 11:38:00

(它继续......) - “类型”是时间表类型,因为它在冬季,夏季等变化。 - “类型”是INT,“time_start”和“time_stop”是VARCHAR(8)

根据现在的时间,我想知道获得 6 个下一个“火车时间”的最有效方法。想象一下,现在是 09:33:10,我想要得到的是这个:

  1        |  09:43:00  | 09:47:00
  1        |  09:55:00  | 09:58:00
  1        |  10:07:00  | 10:10:00
  1        |  10:33:00  | 10:36:00
  1        |  10:45:00  | 10:47:00
  1        |  10:57:00  | 11:00:00

如果我应该在 mysql 表中进行任何更改更改,我也对您的想法持开放态度。提前致谢 ;)

米格尔。

4

4 回答 4

2

You simply could change the VARCHAR type to TIME type, and do a SQL request like SELECT * FROM <yourtable> WHERE time_start > NOW()

于 2013-06-22T11:39:18.537 回答
0

The basic approach is this:

select *
from timetables tt
where tt.time_start > current time
order by tt.time_start
limit 6

There are two challenges with this. The first is midnight. Presumably, if the time is late in the evening, then you want trains in the early morning as well. The second is converting the times to the right format.

select *
from timetable tt
order by (t.time_start > time(now()) desc,
         tt.time_start
limit 6

The trick is to move the where condition into the ordering clause. In effect, this starts the ordering at the current time and continues it after midnight. This allows you to select the six with wrapping.

The time() function should be doing the necessary conversion for the comparison.

于 2013-06-22T11:41:27.497 回答
0

查询将是

SELECT * FROM table_name
WHERE time_start >=time(now()) 
LIMIT 6
于 2013-06-22T11:42:04.703 回答
0

只需将您搜索的时间转换为 int:

$char_time = '09:33:10';
$int_time = (int) str_replace(':','', $char_time);

然后像这样构造你的sql:

$sql = "SELECT *, CAST(REPLACE(time_start, ',', '') AS INT) as mytime 
        FROM yourtable WHERE  mytime > $int_time
        ORDER BY mytime LIMIT 6";

基本上我们上面所做的只是将您的varchar时间字段转换为一种int类型,并使用它进行比较,如果您无法将数据库字段更改为TIME类型,这是一个很好的解决方案。

于 2013-06-22T11:44:09.253 回答