【问题标题】:SQL Server 2008: Unexpected results using SELECT TOPSQL Server 2008:使用 SELECT TOP 的意外结果
【发布时间】:2009-09-15 00:33:54
【问题描述】:

谁能解释我看到的 SQL Server 2008 行为?

给定一个简单的表定义:

Column          Type          Nullability
id (PK)         int           not null
author_id       int           null
title           varchar(255)  not null
body            varchar(MAX)  not null
type            varchar(255)  null
comments_count  int           null

“SELECT * FROM posts ORDER BY cmets_count DESC”返回:

id  author_id  title                               comments_count
--- ---------- ----------------------------------- --------------
1   1          Welcome to the weblog               2             
2   1          So I was thinking                   1             
3   0          I don't have any comments           0             
4   1          sti comments                        0             
5   1          sti me                              0             
6   1          habtm sti test                      0             
7   2          eager loading with OR'd conditions  0             

但“SELECT TOP 3 * FROM posts ORDER BY cmets_count DESC”返回:

id  author_id  title                               comments_count
--- ---------- ----------------------------------- --------------
1   1          Welcome to the weblog               2             
2   1          So I was thinking                   1             
4   1          sti comments                        0             

而不是像我期望的那样返回行 ID 1、2 和 3。

谢谢 尼克

【问题讨论】:

    标签: sql sql-server tsql sql-server-2008


    【解决方案1】:

    当按comments_count 列排序时,id 为 3 和 4 的行有一个平局。标准 SQL 表示,如果存在平局或您未指定任何 ORDER BY 子句,则由供应商实施来确定排序顺序。

    如果你想要某个顺序,我建议你指定顺序:

    SELECT TOP 3 * FROM posts ORDER BY comments_count DESC, id ASC
    

    【讨论】:

    • 可能还值得一提的是,如果您没有明确指定排序,那么它甚至不能保证在不同的查询运行中保持一致。如果ID 不包含在ORDER BY 子句中,那么下一次第三行可能是从3 到7 的任何ID。
    • @Luke:我想你刚才确实提到了。 :-)
    • 感谢您解决这个问题。在像我这样的非 DBA 人员中,这似乎是一种常见的误解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    • 1970-01-01
    • 2010-09-15
    • 2013-09-16
    相关资源
    最近更新 更多