gpt4 book ai didi

mysql - 为什么 PostgreSQL 查询会给出不一致的结果,除非使用 ORDER BY 强制执行可预测的结果排序

转载 作者:行者123 更新时间:2023-11-29 14:17:01 28 4
gpt4 key购买 nike

PostgreSQL doc说:

The query optimizer takes LIMIT into account when generating query plans, so you are very likely to get different plans (yielding different row orders) depending on what you give for LIMIT and OFFSET. Thus, using different LIMIT/OFFSET values to select different subsets of a query result will give inconsistent results unless you enforce a predictable result ordering with ORDER BY. This is not a bug; it is an inherent consequence of the fact that SQL does not promise to deliver the results of a query in any particular order unless ORDER BY is used to constrain the order.

但在 MySQL InnoDB 表中,它们的结果将以 PRIMARY KEY 传递。

为什么查询给出不一致的结果?查询中发生了什么?

最佳答案

Postgres 文档和您的观察告诉您的是,SQL 表中的记录没有内部顺序。相反,数据库表是根据无序的记录集建模的。因此,在以下可以在 MySQL 或 Postgres 上运行的查询中:

SELECT *
FROM yourTable
LIMIT 5

数据库可以随意返回它想要的 5 条记录。在 MySQL 的情况下,如果您看到基于主键的排序,那只是巧合,并且 MySQL 不提供任何此类契约(Contract),因此这种情况总是会发生。

要解决此问题,在使用 LIMIT 时应始终使用 ORDER BY 子句。所以下面的查询是明确定义的:

SELECT *
FROM yourTable
ORDER BY some_column
LIMIT 5

关于mysql - 为什么 PostgreSQL 查询会给出不一致的结果,除非使用 ORDER BY 强制执行可预测的结果排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44535926/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com