我有一个带有TIME列的数据库,我想将该时间的舍入版本与另一个表中的TIME列进行比较。
Example:
root@localhost (mytest) desc ss;
+-------+------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+------+------+-----+---------+-------+
| t | time | YES | | NULL | |
+-------+------+------+-----+---------+-------+
1 row in set (0.01 sec)
root@localhost (mytest) desc tt;
+-------+------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+------+------+-----+---------+-------+
| s | time | YES | | NULL | |
+-------+------+------+-----+---------+-------+
1 row in set (0.00 sec)
root@localhost (mytest) select * from ss;
+----------+
| t |
+----------+
| 16:00:00 |
+----------+
1 row in set (0.00 sec)
root@localhost (mytest) select * from tt;
+----------+
| s |
+----------+
| 15:45:00 |
| 16:00:00 |
| 19:30:00 |
| 17:45:00 |
| 18:00:00 |
| 19:30:00 |
+----------+
需要一个查询来连接ss和tt,其中舍入为tt.s = ss.t
答案 0 :(得分:2)
答案 1 :(得分:1)
我的解决方案是转换为秒,进行数学计算,然后转换回TIME。
select s,hour(s)*3600+minute(s)*60+second(s) time_as_seconds from tt;
+----------+-----------------+
| s | time_as_seconds |
+----------+-----------------+
| 15:45:00 | 56700 |
| 16:00:00 | 57600 |
| 19:30:00 | 70200 |
| 17:45:00 | 63900 |
| 18:00:00 | 64800 |
| 19:30:00 | 70200 |
+----------+-----------------+
6 rows in set (0.00 sec)
对于一个小数据集,我只计算每个表中的“秒”值并进行比较。所以我最终加入了:
1800 * round((hour(tt.s)*3600+minute(tt.s)*60+second(tt.s)) / 1800)
针对
hour(ss.t)*3600+minute(ss.t)*60+second(ss.t)
但是如果引用表(t)中有很多行,或者t.ss上有一个可以加速查询的索引,那么我们必须得到时间值。 SEC_TO_TIME解决了这个问题。
所以,这是一个四舍五入到最近半小时(因此是1800)的例子
select
s,
hour(s)*3600+minute(s)*60+second(s) time_as_seconds,
1800 * round((hour(s)*3600+minute(s)*60+second(s)) / 1800) rounded_to_half_hour,
sec_to_time(1800 * round((hour(s)*3600+minute(s)*60+second(s)) / 1800)) rounded_time
from tt;
+----------+-----------------+----------------------+--------------+
| s | time_as_seconds | rounded_to_half_hour | rounded_time |
+----------+-----------------+----------------------+--------------+
| 15:45:00 | 56700 | 57600 | 16:00:00 |
| 16:00:00 | 57600 | 57600 | 16:00:00 |
| 19:30:00 | 70200 | 70200 | 19:30:00 |
| 17:45:00 | 63900 | 64800 | 18:00:00 |
| 18:00:00 | 64800 | 64800 | 18:00:00 |
| 19:30:00 | 70200 | 70200 | 19:30:00 |
+----------+-----------------+----------------------+--------------+
6 rows in set (0.00 sec)
答案 2 :(得分:0)
假设ss.t
已经四舍五入:
SELECT *
FROM tt
JOIN ss
ON ( SUBTIME(ss.t, '00:30:00.0') <= tt.s )
AND ( tt.s < ADDTIME(ss.t, '00:30:00.0') )