LIMIT 和 OFFSET 返回重复结果

LIMIT and OFFSET returning repeating results

我的查询中似乎有一个错误,导致在我增加 OFFSET 值时重复结果。它应该每页显示 20 个结果。只有 3 个结果符合我的查询要查找的内容,但出于某种原因,其中一些结果会重复出现,即使它们应该只出现在查询结果的第一页上(参见下面的示例)。

SELECT all_users_subbed_to.*, 
    (SELECT COUNT(*) 
     FROM subscribers s2 
     WHERE 
     s2.publisher_id = all_users_subbed_to.publisher_id) 
AS subscribers_sub_count
FROM 
    (SELECT publisher_id, 
     subscriber_id, u2.username AS username, 
     u2.user_photo AS user_photo 
     FROM subscribers s 
     INNER JOIN users u 
     ON (u.id = s.subscriber_id) 
     INNER JOIN users u2 
     ON (u2.id = s.publisher_id) 
     WHERE subscriber_id = 80
    ) 
 AS all_users_subbed_to 
 ORDER BY subscribers_sub_count 
 DESC
 LIMIT 20 
 OFFSET 1;

这个查询的结果是...

| publisher_id | subscriber_id  | username | user_photo | subscribers_sub_count |
|      88      |       80       |  GERPAL1 |  pic.png   |            3          |
|      84      |       80       |  PURPle  |  pic2.png  |            2          |
|      87      |       80       |  Zeeple  |  pic3.png  |            1          |

如果我设置 OFFSET = 2 即 OFFSET 2 结果是 ...

本次查询的结果是


| publisher_id | subscriber_id  | username | user_photo | subscribers_sub_count |
|      84      |       80       |  PURPle  |  pic2.png  |            2          |
|      87      |       80       |  Zeeple  |  pic3.png  |            1          |

...即使这些结果只应在偏移量 = 1 时出现。

如果我设置 OFFSET = 3 即 OFFSET 3 结果是...


| publisher_id | subscriber_id  | username | user_photo | subscribers_sub_count |
|      87      |       80       |  Zeeple  |  pic3.png  |            1          |

...即使这些结果只应在偏移量 = 1 时出现。

知道如何解决这种奇怪的行为吗?如果没有,您是否在我的查询中看到任何错误?

附加信息...

用户table

| id | username   | user_photo |
| 80 | supercookie| userpic.png|
| 88 | GERPAL1    | pic.png    |
| 84 | PURPle     | pic2.png   |
| 87 | Zeeple     | pic3.png   |

订阅者 table

| id | publisher_id | subscriber_id |
| 1  | 88           | 80            |
| 2  | 88           | 84            |
| 3  | 88           | 87            |
| 4  | 84           | 80            |
| 5  | 84           | 88            |
| 6  | 87           | 80            |

根据PostgreSQL documents偏移量意味着OFFSET says to skip that many rows before beginning to return rows

在您的查询中,您添加 LIMIT 20 OFFSET 2 这意味着从 20 个现有行中跳过 2 行,并且跳过前两行并显示上一页的重复行。

您应该使用此公式来计算限制和偏移量:

LIMIT total_record_show OFFSET total_record_show * (page_number - 1)
--- page 1 (total_record_show: 20, page_number: 1)
LIMIT 20 OFFSET 0

--- page 2 (total_record_show: 20, page_number: 2)
LIMIT 20 OFFSET 20

--- page 3 (total_record_show: 20, page_number: 3)
LIMIT 20 OFFSET 40