计算 rails postgresql 查询中的时间差
calculate time difference in rails postgresql query
我需要在我的 rails(有 Postgres 数据库)
中获取时差作为查询结果
Brute Force Approach
我查询了我数据库中的所有项目,然后迭代每条记录,然后计算时间差(小时),这非常慢。
1) @image_retouch_items = ImageRetouchItem.where(:status => '0') = Retrieved all data
2) @image_retouch_items.each do |retouch_item|
latency_date = ((Time.parse(DateTime.now.to_s) - Time.parse(retouch_item.created_at.to_s))/3600).round
end
Optimized
我需要计算查询本身的时间差(小时),如何实现
like - ImageRetouchItem.where(:status => '0').select('(Time.parse(DateTime.now.to_s) - Time.parse(retouch_item.created_at.to_s))/3600).round')
Postgres 可以使用其内部 current_timestamp
:
非常轻松地为您完成此操作
ImageRetouchItem.where(:status => '0')
.select("*, round(extract(epoch from(current_timestamp - created_at)) / 3600)::int as latency_date")
current_timestamp - created_at
将 return 一个间隔。通过从该间隔中提取 epoch
,我们将其转换为秒数,然后除以 3600 以使用 Postgres round()
函数得到小时数和舍入数。我继续使用 ::int
将结果转换为整数,但这是可选的。
image_retouch_item 对象现在将有一个 latency_date
属性,该属性将包含以小时为单位的延迟,四舍五入到最接近的小时。
我需要在我的 rails(有 Postgres 数据库)
中获取时差作为查询结果Brute Force Approach
我查询了我数据库中的所有项目,然后迭代每条记录,然后计算时间差(小时),这非常慢。
1) @image_retouch_items = ImageRetouchItem.where(:status => '0') = Retrieved all data
2) @image_retouch_items.each do |retouch_item|
latency_date = ((Time.parse(DateTime.now.to_s) - Time.parse(retouch_item.created_at.to_s))/3600).round
end
Optimized
我需要计算查询本身的时间差(小时),如何实现
like - ImageRetouchItem.where(:status => '0').select('(Time.parse(DateTime.now.to_s) - Time.parse(retouch_item.created_at.to_s))/3600).round')
Postgres 可以使用其内部 current_timestamp
:
ImageRetouchItem.where(:status => '0')
.select("*, round(extract(epoch from(current_timestamp - created_at)) / 3600)::int as latency_date")
current_timestamp - created_at
将 return 一个间隔。通过从该间隔中提取 epoch
,我们将其转换为秒数,然后除以 3600 以使用 Postgres round()
函数得到小时数和舍入数。我继续使用 ::int
将结果转换为整数,但这是可选的。
image_retouch_item 对象现在将有一个 latency_date
属性,该属性将包含以小时为单位的延迟,四舍五入到最接近的小时。