如何允许1到10秒的容差?
我有两个有时间戳的表,但却有1-10秒。我正在使用内部联接来比较它们。我在两个表中都有匹配的电话号码(列)但不能使它们与时间戳匹配(仅限时间)。为了允许一定的容差,我可以使用像cast(DateCreated as Time) = cast(TIMESTAMP as time) + 5
这样的表达式。但我不想每隔一段时间这样做。
SELECT Time_To_Sec(cast("table1_DateCreated" as time)) as DateCreated
, Time_To_Sec(cast("table2"."Timestamp" as time)) as Timestampe
, "Direction","FromTW", "ToTW", "table2"."ANI","table2"."CALL ID"
, "table2"."Disposition"
FROM "calls and time"
INNER JOIN "table2" on cast(DateCreated as Time)=cast(TIMESTAMP as time)+5
and FromTW="table2"."ANI"
如果可能,我希望看到以下结果:
table1(DateCreated) | table2(Timestamp) | compared results
---------------------+---------------------+-----------------
5000 | 5005 | table3
5001 | 5009 | table3
5001 | 5050 | not in table3
如果符合条件,则会将其发送至表3,但如果不符合条件,则不会将其发送至表3。
使用Zoho报告,因此我不确定他们使用的是哪种类型的数据库。 Postgres,MySQL等
答案 0 :(得分:3)
如果两个表中的时间戳都可以是off by 1-10 seconds
,那么逻辑上遵循匹配的最大容差 20 sceonds (+/- 10 on每侧)。
经过 Postgres 测试:
SELECT *
FROM "calls and time" t1
JOIN table2 t2 ON t2."TIMESTAMP" BETWEEN t1."DateCreated" - interval '20 sec'
AND t1."DateCreated" + interval '20 sec';
WHERE t1."FromTW" = t2."ANI" -- FromTW or "FromTW" ?
这是sargable表达式,允许在x
上使用索引:
x BETWEEN y - interval '20 sec'
AND y + interval '20 sec'
"calls and time"
,"TIMESTAMP"
,"FromTW"
是非常不幸的标识符,顺便说一句。坚持使用合法的,不带引号的名称来节省一些麻烦。
答案 1 :(得分:0)
检查两个时间戳的绝对差异,它们是伪代码:
if (abs($timestamp1 - $timestamp2) <= $tolerance) { ... }