2

我遇到了一个问题,即 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;

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

4

1 回答 1

5

对于所有结果行来说,这听起来像是categories.position并且photos.display_priority不是唯一的。当用于排序的值都相等时,数据库服务器不会指定行的顺序;即使表数据在查询之间没有更改,也可以按任何顺序自由返回它们。

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

于 2013-08-28T22:17:07.620 回答