Postgres订购不一致

时间:2013-08-28 22:12:45

标签: postgresql

我遇到的问题是postgres有序的结果不是一致的。我按多个字段排序:ORDER BY categories.position ASC,photos.display_priority

我注意到这一点,因为当您浏览网站时,结果会被分页。我找到了一个从第1页到第2页的案例,在第2页的顶部,我看到了第1页底部附近的照片。

这是我的第1页查询:

SELECT "photos".*
FROM "photos"
    INNER JOIN "categories" ON "categories"."id" = "photos"."category_id"
WHERE "photos"."category_id" IN (221, 633, 377, 216, 634)
    AND (photos.caption IS NOT NULL
        AND photos.category_id IS NOT NULL
        AND photos.rights IS NOT NULL
        AND photos.deleted IS NULL)
ORDER BY categories.position ASC, photos.display_priority DESC
LIMIT 25 OFFSET 0;

我的第2页查询:

SELECT "photos".*
FROM "photos"
    INNER JOIN "categories" ON "categories"."id" = "photos"."category_id"
WHERE "photos"."category_id" IN (221, 633, 377, 216, 634)
    AND (photos.caption IS NOT NULL
        AND photos.category_id IS NOT NULL
        AND photos.rights IS NOT NULL
        AND photos.deleted IS NULL)
ORDER BY categories.position ASC, photos.display_priority DESC
LIMIT 25 OFFSET 25;

当我尝试同时获取两个页面(偏移0,限制50)并检查两组之间的阈值时,没有重复,没有意外。

SELECT "photos".*
FROM "photos"
    INNER JOIN "categories" ON "categories"."id" = "photos"."category_id"
WHERE "photos"."category_id" IN (221, 633, 377, 216, 634)
    AND (photos.caption IS NOT NULL
        AND photos.category_id IS NOT NULL
        AND photos.rights IS NOT NULL
        AND photos.deleted IS NULL)
ORDER BY categories.position ASC, photos.display_priority DESC
LIMIT 50 OFFSET 0;

我的查询有问题吗?是否有我不理解的限制和顺序的操作顺序?

1 个答案:

答案 0 :(得分:5)

听起来categories.positionphotos.display_priority对于所有结果行都不是唯一的。当用于排序它们的值全部相等时,数据库服务器不指定行的顺序;即使表格数据在查询之间没有变化,也可以按任意顺序返回它们。

要获得一致的排序,您必须添加第三个排序键,保证所有行都是唯一的,例如该特定行的标识值。