通过删除强制转换和函数来提高查询效率



我有以下查询,它按预期工作。

如果存在匹配的id并且时间戳在我要查找的范围内,它会更新。

我无法根据准确的时间戳值进行验证,因为传入的请求只会大致匹配时间(缺少几毫秒(,因此必须通过如下截断来找到匹配。

UPDATE myTable SET code=1, WHERE id=50 
and 
start_ts >= date_trunc('day', cast('2020-10-03 13:34:51.947000' as TIMESTAMP))
and 
start_ts < date_trunc('day', cast('2020-10-03 13:34:51.947000' as TIMESTAMP)) + interval '1 day';

有没有一种方法可以做到这一点,而不必使用date_trunc方法和casting,或者至少减少只执行一次的casting,因为它是重复的?

请提供建议。谢谢

您的查询很好。为了提高性能,您需要myTable(id, start_ts)上的索引。

在Postgres中,您应该能够执行:

update mytable set code=1
where 
id=50 
and start_ts >= '2020-10-03 13:34:51.947000'::date
and start_ts <  '2020-10-03 13:34:51.947000'::date + interval '1 day';

最新更新