为什么Top,OFFset fetch,Rownumber查询只是通过改变升序和降序给出不同的结果?

时间:2016-02-18 11:54:30

标签: database database-design database-connection relational-database database-schema

使用AdventureWorks2012数据库

步骤1:执行以下查询:

select *
from 
    (select
         ROW_NUMBER() OVER(order by listprice desc) AS RowNumber,*
     from Production.Product) as a
where 
    a.RowNumber between 1 and 2

select *
from Production.Product
order by ListPrice desc
offset 0 rows fetch next 2 rows only

select top 2 Productid, ListPrice
from Production.Product
order by ListPrice desc

步骤2:现在执行以下查询:

select *
from 
    (select
         ROW_NUMBER() OVER(order by listprice asc) AS RowNumber,*
     from Production.Product) as a
where 
     a.RowNumber between 1 and 2

select *
from Production.Product
order by ListPrice asc
offset 0 rows fetch next 2 rows only

select top 2 Productid, ListPrice 
from Production.Product 
order by ListPrice asc

在两种情况下查看产品ID(对于DESC和ASC)

1 个答案:

答案 0 :(得分:2)

这一点都不奇怪。您学到的是多行具有相同的listprice值。当listprice存在关联时,对于具有相同值的键,排序 indeterminate

换句话说,SQL Server(和一般数据库)中的排序不稳定。多次运行相同的查询可以返回不同的顺序。同样,对查询的细微更改可能会导致不同的顺序 - 对于具有相同值的键。

实际上这很容易理解。 SQL表表示无序集。因此,他们没有自然排序。数据库无法对具有相同键值的行进行规范排序。

要解决此问题,只需在订购中添加一个唯一ID,例如:

order by listprice desc, productid

添加额外的唯一键可使排序稳定。