我有一张包含位置和时间信息的表gps(时间,纬度,长度)。 我有一个表事件,可以保留某些事件(时间)的时间。
我需要sql(最好是mysql)创建一个新表:header('Content-Type: application/json');
$arr=array("Download" => "http://www.exemple.com/file");
$json = json_encode($arr);
print_r($json);
对于表事件中的每个记录,注册表events_with_gps
的寄存器的位置(lat,long)更接近事件。
示例:
gps
而且,是否可以将gps:
11:00:00, 10, 10
11:05:00, 14, 14
11:10:00, 18, 18
11:15:00, 20, 20
11:20:00, 22, 22
events:
11:06:02
11:14:09
events_with_gps:
11:06:02, 14, 14
11:14:09, 20, 20
中的位置设置为上一个和下一个gps寄存器之间的平均值?
events_with_gps
答案 0 :(得分:1)
在最近时间执行联接的一种方法是首先使用CROSS JOIN
来计算gps
和event
表格中时间列之间的所有可能差异。
以下查询:
SELECT e.`time` AS etime, g.`time` AS gtime, g.lat, g.`long`,
ABS(TIMEDIFF(e.`time`, g.`time`)) AS diff
FROM events AS e
CROSS JOIN gps AS g
ORDER BY e.`time`, diff
产生以下输出:
etime gtime lat long diff
------------------------------------------
11:06:02 11:05:00 14 14 102
11:06:02 11:10:00 18 18 358
11:06:02 11:00:00 10 10 602
11:06:02 11:15:00 20 20 858
11:06:02 11:20:00 22 22 1358
11:14:09 11:15:00 20 20 51
11:14:09 11:10:00 18 18 409
11:14:09 11:20:00 22 22 551
11:14:09 11:05:00 14 14 909
11:14:09 11:00:00 10 10 1409
如果您GROUP BY
etime并使用GROUP_CONCAT
,您可以从上述结果集中选择具有最小diff
值的记录。您可以将JOIN
这些记录返回gps
,以便将记录插入events_with_gps
:
SELECT t.`time`, g.lat, g.`long`
FROM (
SELECT e.`time`,
SUBSTRING_INDEX(
GROUP_CONCAT(g.`time`
ORDER BY ABS(TIMEDIFF(e.`time`, g.`time`))), ',', 1) AS matchedTime
FROM events AS e
CROSS JOIN gps AS g
GROUP BY e.`time` ) t
INNER JOIN gps AS g ON CAST(t.matchedTime AS TIME) = g.`time`
<强>输出:强>
time lat long
-----------------------
'11:06:02' 14 14
'11:14:09' 20 20
要获取第二个结果集,您可以使用以下查询获取每个gps
记录的上一个和下一个events
记录:
SELECT e.`time` as etime,
(SELECT `time`
FROM gps AS g
WHERE g.`time` <= e.`time`
ORDER BY g.`time` DESC
LIMIT 1) AS prevTime,
(SELECT `time`
FROM gps AS g
WHERE g.`time` > e.`time`
ORDER BY g.`time`
LIMIT 1) AS nextTime
FROM events AS e
输出
etime prevTime nextTime
------------------------------
11:06:02 11:05:00 11:10:00
11:14:09 11:10:00 11:15:00
您现在可以将上述内容用作派生表,以便加入gps
并获取“上一个”和“下一个”lat
和{{1} }值:
long
<强>输出:强>
SELECT t.etime, (g1.lat + g2.lat) /2 , (g1.`long` + g2.`long`) / 2
FROM (
SELECT e.`time` as etime,
(SELECT `time`
FROM gps AS g
WHERE g.`time` <= e.`time`
ORDER BY g.`time` DESC
LIMIT 1) AS prevTime,
(SELECT `time`
FROM gps AS g
WHERE g.`time` > e.`time`
ORDER BY g.`time`
LIMIT 1) AS nextTime
FROM events AS e ) t
INNER JOIN gps AS g1 ON t.prevTime = g1.time
INNER JOIN gps AS g2 ON t.nextTime = g2.time