我有一个带有时间戳(DATETIME)值的表。
表MyLog:
+----------+---------------------+--------+
+
| logNo | timestamp | temp |
|
+----------+---------------------+--------+
+
| 1 | 2016-04-24 15:57:56 | 29.6 |
|
| 2 | 2016-04-24 16:59:24 | 29.7 |
|
| 3 | 2016-04-24 18:01:52 | 29.6 |
|
| 4 | 2016-04-24 18:59:20 | 29.6 |
+----------+---------------------+--------+
我有另一张桌子(HourLog)可以拉出“临时表”。来自' MyLog'的价值每个小时的最高点(HH:00:00),其值为'时间戳'最接近'时间戳' HourLog中的值(因为时间戳值不能总是正好是HH:00:00)。
HourLog:
+----------+---------------------+--------+
+
|logNo | timestamp | temp |
|
+----------+---------------------+--------+
+
| 1 | 2016-04-24 00:00:00 | 29.6 |
|
| 2 | 2016-04-24 01:00:00 | 29.7 |
|
| 3 | 2016-04-24 02:00:00 | 29.6 |
|
| 4 | 2016-04-24 03:00:00 | 29.6 |
|
| 5 | 2016-04-24 04:00:00 | 29.7 |
|
| 6 | 2016-04-24 05:00:00 | 29.8 |
|
| 7 | 2016-04-24 06:00:00 | 30.2 |
|
| 8 | 2016-04-24 07:00:00 | 30.1 |
|
| 9 | 2016-04-24 08:00:00 | 30.1 |
|
| 10 | 2016-04-24 09:00:00 | 30.1 |
|
| 11 | 2016-04-24 10:00:00 | 30.0 |
|
| 12 | 2016-04-24 11:00:00 | 30.1 |
|
| 13 | 2016-04-24 12:00:00 | 30.1 |
|
| 14 | 2016-04-24 13:00:00 | 29.9 |
|
| 15 | 2016-04-24 14:00:00 | 29.8 |
|
| 16 | 2016-04-24 15:00:00 | 29.6 |
|
| 17 | 2016-04-24 16:00:00 | 29.6 |
|
| 18 | 2016-04-24 17:00:00 | 29.7 |
|
| 19 | 2016-04-24 18:00:00 | 29.6 |
|
| 20 | 2016-04-24 19:00:00 | 29.6 |
+----------+---------------------+--------+
我想写的查询应该能够查看MyLog中的时间戳值,获取最接近当前小时的值并插入' temp'使用(HH:00:00)时间戳记将值写入HourLog。
一个例子: MyLog
+----------+---------------------+--------+
+
| logNo | timestamp | temp |
|
+----------+---------------------+--------+
+
| 101 | 2016-04-24 17:57:56 | 29.6 |
|
| 102 | 2016-04-24 17:59:24 | 29.7 |
|
| 103 | 2016-04-24 18:01:52 | 29.6 |
|
| 104 | 2016-04-24 18:04:20 | 29.6 |
+----------+---------------------+--------+
查询选择logNo 102,因为它的时间戳值最接近小时的最高点(18:00:00),并插入' temp'值为HourLog logNo 74
HourLog:
+----------+---------------------+--------+
+
| logNo | timestamp | temp |
|
+----------+---------------------+--------+
+
| 71 | 2016-04-24 15:00:00 | 28.6 |
|
| 72 | 2016-04-24 16:00:00 | 28.7 |
|
| 73 | 2016-04-24 17:00:00 | 30.1 |
|
| 74 | 2016-04-24 18:00:00 | 29.6 |
+----------+---------------------+--------+
如何在MySQL中编写这样的预定查询?
答案 0 :(得分:1)
忍受我,但尝试创建一个像这样的SQL文件,称之为query.sql
:
SET @n = NOW();
INSERT INTO HourLog
SELECT 0, @n, X.temp (
SELECT
TIMESTAMPDIFF(SECOND, timestamp, @n) diff,
temp
FROM MyLog
ORDER BY diff ASC
LIMIT 1
) X;
然后创建一个调用该文件(script.sh
)的shell脚本:
mysql --login-path=[your login path] [your database] < /path/to/query.sql
然后你应该能够像这样调用一个cron工作:
0 * * * * /path/to/script.sh