gpt4 book ai didi

sql - SQL 是否可以使用 ORDER BY 为同一查询的两次运行返回不同的结果?

转载 作者:行者123 更新时间:2023-12-03 19:55:54 25 4
gpt4 key购买 nike

我有下表:

CREATE TABLE dbo.TestSort
(
Id int NOT NULL IDENTITY (1, 1),
Value int NOT NULL
)
Value列可以(并且预计)包含重复项。
我们还假设表中已经有 1000 行。

我试图证明一个关于不稳定排序的观点。

鉴于此查询从前 1000 个插入的结果中返回 10 个结果的“页面”:
SELECT TOP 10 * FROM TestSort WHERE Id <= 1000 ORDER BY Value

我的直觉告诉我,如果 Value,这个查询的两次运行可能会返回不同的行。列包含重复值。

我基于以下事实:
  • 排序不稳定
  • 如果在两次查询运行之间在表中插入新行,则可能会创建 B 树的重新平衡(Value 列可能已编入索引或未编入索引)

  • 编辑:为了完整性:我假设行一旦插入就永远不会改变,也永远不会被删除。

    相反,具有稳定排序(也按 Id 排序)的查询应始终返回相同的结果,因为 ID s 是唯一的:
    SELECT TOP 10 * FROM TestSort WHERE Id <= 1000 ORDER BY Value, Id

    问题是:我的直觉正确吗?如果是,您能否提供一个会产生不同结果的实际操作示例(至少“在您的机器上”)?您可以修改查询,在 Values 上添加索引列等
    我不关心确切的查询,但关心原则。

    我正在使用 MS SQL Server (2014),但对任何 SQL 数据库的答案都同样满意。

    如果不是,那为什么呢?

    最佳答案

    你的直觉是正确的。在 SQL 中,对 order by 的排序不稳定。因此,如果您有领带,则可以按任何顺序退回。而且,顺序可以从一次运行更改为另一运行。

    documentation有点解释这个:

    Using OFFSET and FETCH as a paging solution requires running the query one time for each "page" of data returned to the client application. For example, to return the results of a query in 10-row increments, you must execute the query one time to return rows 1 to 10 and then run the query again to return rows 11 to 20 and so on. Each query is independent and not related to each other in any way. This means that, unlike using a cursor in which the query is executed once and state is maintained on the server, the client application is responsible for tracking state. To achieve stable results between query requests using OFFSET and FETCH, the following conditions must be met:

    • The underlying data that is used by the query must not change. That is, either the rows touched by the query are not updated or all requests for pages from the query are executed in a single transaction using either snapshot or serializable transaction isolation. For more information about these transaction isolation levels, see SET TRANSACTION ISOLATION LEVEL (Transact-SQL).

    • The ORDER BY clause contains a column or combination of columns that are guaranteed to be unique.



    虽然这特指 offset/ fetch ,它显然适用于在没有这些子句的情况下多次运行查询。

    关于sql - SQL 是否可以使用 ORDER BY 为同一查询的两次运行返回不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33148338/

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