我不确定我的问题是否适用于SQL查询。
我有以下两个Mysql表:
表a: 该表每20秒获得一个新值
a.Time a.Value
2015-05-14 07:36:36 49
2015-05-14 07:36:56 49
2015-05-14 07:37:16 49
2015-05-14 07:37:36 49
2015-05-14 07:37:56 50
2015-05-14 07:38:16 50
2015-05-14 07:38:36 50
2015-05-14 07:38:56 49
2015-05-14 07:39:16 49
2015-05-14 07:39:36 49
2015-05-14 07:39:56 49
2015-05-14 07:40:16 50
2015-05-14 07:40:36 50
2015-05-14 07:40:56 50
2015-05-14 07:41:16 49
2015-05-14 07:41:36 49
2015-05-14 07:41:56 50
2015-05-14 07:42:16 50
2015-05-14 07:42:36 49
2015-05-14 07:42:56 49
2015-05-14 07:43:16 49
2015-05-14 07:43:36 49
2015-05-14 07:43:56 49
2015-05-14 07:44:06 49
表b 该表每次更改值都是新记录
b.Time b.Value
2015-05-14 07:34:50 1500
2015-05-14 07:38:52 2000
2015-05-14 07:40:52 0
2015-05-14 07:42:31 1500
结果应如下所示
a.Time a.Value b.Time b.Value
2015-05-14 07:36:36 49 2015-05-14 07:34:50 1500
2015-05-14 07:36:56 49 2015-05-14 07:34:50 1500
2015-05-14 07:37:16 49 2015-05-14 07:34:50 1500
2015-05-14 07:37:36 49 2015-05-14 07:34:50 1500
2015-05-14 07:37:56 50 2015-05-14 07:34:50 1500
2015-05-14 07:38:16 50 2015-05-14 07:34:50 1500
2015-05-14 07:38:36 50 2015-05-14 07:34:50 1500
2015-05-14 07:38:56 49 2015-05-14 07:38:52 2000
2015-05-14 07:39:16 49 2015-05-14 07:38:52 2000
2015-05-14 07:39:36 49 2015-05-14 07:38:52 2000
2015-05-14 07:39:56 49 2015-05-14 07:38:52 2000
2015-05-14 07:40:16 50 2015-05-14 07:38:52 2000
2015-05-14 07:40:36 50 2015-05-14 07:38:52 2000
2015-05-14 07:40:56 50 2015-05-14 07:40:52 0
2015-05-14 07:41:16 49 2015-05-14 07:40:52 0
2015-05-14 07:41:36 49 2015-05-14 07:40:52 0
2015-05-14 07:41:56 50 2015-05-14 07:40:52 0
2015-05-14 07:42:16 50 2015-05-14 07:40:52 0
2015-05-14 07:42:36 49 2015-05-14 07:42:31 1500
2015-05-14 07:42:56 49 2015-05-14 07:42:31 1500
2015-05-14 07:43:16 49 2015-05-14 07:42:31 1500
2015-05-14 07:43:36 49 2015-05-14 07:42:31 1500
2015-05-14 07:43:56 49 2015-05-14 07:42:31 1500
2015-05-14 07:44:06 49 2015-05-14 07:42:31 1500
表a中的时间戳应该是表b中的下一个较小的时间戳!
知道查询的外观吗?
非常感谢!
答案 0 :(得分:1)
使用按TIME
和LIMIT 1
订购的子查询,从B获得一条最高记录,时间少于当前A.时间:
SELECT
a.Time,
a.Value,
(SELECT Time FROM B WHERE B.Time<=A.Time ORDER BY B.Time DESC LIMIT 1)
as B_Time,
(SELECT Value FROM B WHERE B.Time<=A.Time ORDER BY B.Time DESC LIMIT 1)
as B_Value
FROM A
ORDER BY A.Time