每次按时间戳排序时都会返回相同的行

时间:2011-04-30 09:45:44

标签: sql postgresql ruby-on-rails-3

当我按created_at(时间戳)排序时,我的postgresql数据库会保持返回相同的最后一行,并限制结果数。

最后一个结果始终是同一行。看看这些结果中的最后一个ID:

looked=# select id,created_at from businesses order by created_at asc limit 2;
id |          created_at
----+-------------------------------
38 | 2011-04-30 18:31:23.923475+10
20 | 2011-04-30 18:31:23.923475+10
(2 rows)

looked=# select id,created_at from businesses order by created_at asc limit 5;
id  |          created_at
------+-------------------------------
38 | 2011-04-30 18:31:23.923475+10
436 | 2011-04-30 18:31:23.923475+10
1334 | 2011-04-30 18:31:23.923475+10
2845 | 2011-04-30 18:31:23.923475+10
20 | 2011-04-30 18:31:23.923475+10
(5 rows)

looked=# select id,created_at from businesses order by created_at asc limit 10;
id  |          created_at
------+-------------------------------
38 | 2011-04-30 18:31:23.923475+10
436 | 2011-04-30 18:31:23.923475+10
1334 | 2011-04-30 18:31:23.923475+10
2845 | 2011-04-30 18:31:23.923475+10
3381 | 2011-04-30 18:31:23.923475+10
1089 | 2011-04-30 18:31:23.923475+10
822 | 2011-04-30 18:31:23.923475+10
2310 | 2011-04-30 18:31:23.923475+10
1773 | 2011-04-30 18:31:23.923475+10
20 | 2011-04-30 18:31:23.923475+10
(10 rows)

2 个答案:

答案 0 :(得分:1)

所有created_at值都相同。 ORDER BY和LIMIT将任意created_at为最低值的行集中选择行

你必须添加一个额外的排序条件来“打破”这些行。我在这里添加了id

select id,created_at from businesses
order by created_at asc, id limit 5;

答案 1 :(得分:1)

每行的created_at值都相同。 Postgres正在任意打破关系。如果您想要更多控制/可预测性,请添加另一个排序条件(例如在ID上)。