使用内部联接来加入mySQL列,时间戳略有不同

时间:2018-02-04 03:20:31

标签: mysql mariadb sql-optimization

我想从两个数据库的不同表中查询,时间戳作为常用功能。目前,我的结果是空的,有多个警告。我的查询设计是:

SELECT tableA.ts, tableB.column1, time_to_sec(tableC.column1) as duration, 
tableD.column1 FROM databaseA.tableA \
INNER JOIN databaseB.tableB ON tableA.ts = tableB.ts \
BETWEEN tableA.ts - INTERVAL 50 SECOND AND tableA.ts + INTERVAL 50 SECOND \
INNER JOIN databaseB.tableC ON tableB.ts = tableC.ts \
BETWEEN tableB.ts - INTERVAL 50 SECOND AND tableB.ts + INTERVAL 50 SECOND \
INNER JOIN databaseB.tableD ON tableC.ts = tableD.ts \
BETWEEN tableC.ts - INTERVAL 50 SECOND AND tableC.ts + INTERVAL 50 SECOND \
WHERE TIME(tableA.ts) between '08:59:00' AND '09:01:00'; #getting values at 9am here

表A来自数据库A.表B,C,D来自数据库B. ts是指时间戳,我根据公共时间戳在表之间加入。但是,由于时间戳之间略微偏离了几秒钟,我添加了例如BETWEEN tableB.ts - INTERVAL 50 SECOND AND tableB.ts + INTERVAL 50 SECOND之间的INNER JOIN。我认为这可能会导致问题,但是,我不太确定。如果是这样,我该如何修改这个问题呢?

1 个答案:

答案 0 :(得分:1)

更好的方法是使用内置函数,例如ABSTIMESTAMPDIFF

SELECT tableA.ts, tableB.column1, TIME_TO_SEC(tableC.column1) as duration, tableD.column1 
FROM databaseA.tableA
INNER JOIN databaseB.tableB ON ABS(TIMESTAMPDIFF(SECOND, tableA.ts, tableB.ts)) <= 50
INNER JOIN databaseB.tableC ON ABS(TIMESTAMPDIFF(SECOND, tableB.ts, tableC.ts)) <= 50
INNER JOIN databaseB.tableD ON ABS(TIMESTAMPDIFF(SECOND, tableC.ts, tableD.ts)) <= 50
WHERE TIME(tableA.ts) between '08:59:00' AND '09:01:00';