【问题标题】:Repeating some rows in some offsets in the PostgreSQL在 PostgreSQL 中的某些偏移量中重复某些行
【发布时间】:2020-11-01 14:47:09
【问题描述】:

当我同时使用 select、join、order by、offset 和 limit 时,为什么有时会在不同的偏移量中重复行?

select * from users u
left join posts p on p.user_id = u.id
order by u.id
offset 0, limit 20

【问题讨论】:

  • 能否提供您收到的与预期的结果
  • 是的,当然。请稍候。
  • 是否有可能在对数据库的不同调用之间插入/删除了记录?
  • 我不确定!!!

标签: database postgresql select sql-order-by pagination


【解决方案1】:

问题是您正在使用包含重复值的列 (amount) 进行排序。您的 order by 子句不是确定性的,因此结果不稳定。

一个简单的解决方案是使用第二个排序标准来打破平局(它看起来user(id)可以做到这一点):

select *                                  -- better enumerate the columns here
from wallets w
inner join users u on u.id = w.user_id    -- your "left join" is actually "inner join"
where u.role = 'tester' and w.amount > 0
order by w.amount, u.id                   -- here is the second sorting criteria
offset 0, limit 20

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-24
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多