具有 BETWEEN 时间戳的 SQL 查询出现意外结果

问题描述 投票:0回答:1

我创建了一个小测试应用程序来追踪我在 Heroku 上使用 Postgres 时遇到的问题:http://snippi.com/s/xd511rf

正如您在第49行中看到的那样,我想检索今天创建的所有条目。这将是我使用 Ruby Gem DataMapper 测试数据的前两项。

当我在我的笔记本(Ubuntu 12.10、HP、Ruby 1.9.3)上运行这个应用程序时,我得到了这个结果,这是正确的:

[
{
    "id": 1,
    "text": "Working on some awsomenewss",
    "category": 0,
    "starttime": "2013-03-21T15:56:00+01:00",
    "endtime": "2013-03-21T18:26:00+01:00",
    "creation": "2013-03-21T16:15:21+01:00"
},
{
    "id": 2,
    "text": "facebooking",
    "category": 0,
    "starttime": "2013-03-21T20:48:00+01:00",
    "endtime": "2013-03-21T22:26:00+01:00",
    "creation": "2013-03-21T16:15:21+01:00"
}
]

在我的调试控制台中记录了此 SQL 查询:

SELECT "id", "text", "category", "starttime", "endtime", "creation" 
  FROM "entries" 
  WHERE "starttime" 
    BETWEEN '2013-03-21T00:00:00+00:00' 
      AND '2013-03-21T23:59:59+00:00' 
  ORDER BY "id"

但是将应用程序推送到 Heroku 后,出现了一个非常奇怪的错误。当我现在运行它时(http://afternoon-everglades-4239.herokuapp.com/),这就是响应:

[]

为什么是空的?

数据肯定在数据库中,Heroku 的 Dataclip 证明了这一点:https://dataclips.heroku.com/hygziosyxwperyctwfbhjzgbzhbj

此外,当我通过“heroku pg:psql”手动运行 SQL 命令时,它实际上可以使用此输出:

 身份证 |            文字|类别 |      开始时间 |       末日 |      创建       
---+-----------------------------+----------+---- ------------------+---------------------+---------- ------------
  1 |正在研究一些很棒的新闻|        0 | 2013-03-21 15:56:00 | 2013-03-21 18:26:00 | 2013-03-21 16:15:21
  2 |脸书 |        0 | 2013-03-21 20:48:00 | 2013-03-21 22:26:00 | 2013-03-21 16:15:21
(2 行)

日志不包含任何错误或更多信息。 我在两种情况下(生产和本地)都使用了远程 Heroku PostgreSQL 数据库

那么为什么这不起作用?

sql ruby postgresql heroku timestamp-with-timezone
1个回答
3
投票

检查列的数据类型和您的时区。您可能会混淆

timestamp with time zone
timestamp

看起来您的表中有

timestamp
,但使用
timestamptz
进行查询。这样,这一切都取决于您会话的本地时区(如果没有另外指定,则默认为服务器的时区。)

将两者切换为

timestamptz
,如果时区与您完全无关,则将其切换为
timestamp
。 (如有疑问,请使用
timestamptz
。)

不是问题的原因,但您的查询可能应该是:

SELECT id, text, category, starttime, endtime, creation 
FROM   entries 
WHERE  starttime >= timestamp '2013-03-21' -- defaults to 00:00 time
AND    starttime <  timestamp '2013-03-22'
ORDER  BY id;
由于小数,对于

a BETWEEN x AND y

 类型,
timestamp
几乎总是错误
!您的查询会用
starttime = '2013-03-21T23:59:59.123+00'
做什么?

© www.soinside.com 2019 - 2024. All rights reserved.