SQL Server 2008:使用SELECT TOP的意外结果

2 sql t-sql sql-server sql-server-2008

任何人都可以解释我看到的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
Run Code Online (Sandbox Code Playgroud)

"SELECT*FROM posts ORDER BY comments_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             
Run Code Online (Sandbox Code Playgroud)

但"SELECT TOP 3*FROM posts ORDER BY comments_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             
Run Code Online (Sandbox Code Playgroud)

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

谢谢尼克

Bil*_*win 15

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

如果您需要特定订单,我建议您指定订单:

SELECT TOP 3 * FROM posts ORDER BY comments_count DESC, id ASC
Run Code Online (Sandbox Code Playgroud)