当我从 Postgresql
数据库查询 exponent value
时遇到问题。
当我查询如下时:
select t,v from c1.hour where f = 22 and date_trunc('day',t - '1 hour'::INTERVAL) = '2016-02-26 00:00:00' order by t ;
t | v
---------------------+-------------
2016-02-26 02:00:00 | 1.45642e+09
它返回指数值。
然后我将指数值展开如下:
select t,to_char(v, '99999999999999999D99') from c1.hour where f = 22 and date_trunc('day',t - '1 hour'::INTERVAL) = '2016-02-26 00:00:00' order by t ;
t | to_char
---------------------+--------------------
2016-02-26 02:00:00 | 1456418944
但是当我使用ActiveRecord
获取数据时,结果似乎不正确。
#<Aws1:0x00000007940ca8 t: Fri, 26 Feb 2016 02:00:00 JST +09:00, f: 22, v: 1456420000.0>
我的预期结果是: 1456418944
而不是 1456420000.0
。
我不明白为什么 Rails
会返回这个结果。请问我可以得到一些帮助吗?
一些信息:我使用了Rails 4.2.5
、Ruby 2.2.3
和gem 'pg', '~> 0.15'
更新:这是小时表
aws1=# \d hour
Table "c1.hour"
Column | Type | Modifiers
--------+-----------------------------+-----------
t | timestamp without time zone | not null
f | smallint | not null
h | smallint | not null
v | real |
q | smallint |
Indexes:
"hour_key" PRIMARY KEY, btree (t, f, h)
最佳答案
我认为这是一个 PostgreSQL 问题,而不是 Rails。 Rails 只显示返回的内容。它不会以任何方式调整查询结果。如我所见,当 PG 明确查询此字段时,它返回 1.45642e+09
,这显然与您在 Rails 中看到的完全相同 (1456420000.0
。)
因此,问题将重述为“如何强制 PG 返回精确值?”好吧,您在 OP 中回答了这个问题:需要显式类型转换 to_char(v, '99999999999999999D99')
。
总结:我能想到的解决方案有两种:
- 在PG中引入新的计算字段,由触发器填充为
to_char(v, '99999999999999999D99')
,或者 - 在 Rails 中使用显式查询。
后者看起来像:
Aws1.connection.execute %Q{
SELECT t, to_char(v, '99999999999999999D99')
FROM c1.hour
WHERE f = 22
AND date_trunc('day',t - '1 hour'::INTERVAL) = '2016-02-26 00:00:00'
ORDER BY t
}
关于ruby-on-rails - 来自 postgresql 的 Rails 自动轮毫秒查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35643811/