加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sql – 没有ORDER BY的ROW_NUMBER

发布时间:2020-12-12 06:43:09 所属栏目:MsSql教程 来源:网络整理
导读:我要在现有查询中添加行号,以便我可以跟踪已添加到Redis中的数据量.如果我的查询失败,那么我可以从该行开始,而不是在其他表中更新. 查询从表中获取1000行之后的数据 SELECT * FROM (SELECT *,ROW_NUMBER() OVER (Order by (select 1)) as rn ) as X where rn
我要在现有查询中添加行号,以便我可以跟踪已添加到Redis中的数据量.如果我的查询失败,那么我可以从该行开始,而不是在其他表中更新.

查询从表中获取1000行之后的数据

SELECT * FROM (SELECT *,ROW_NUMBER() OVER (Order by (select 1)) as rn ) as X where rn > 1000

查询工作正常.如果有任何方式我可以获得行没有不使用order by.

这里选择1是什么?

查询是否已优化,或者我可以通过其他方式执行此操作.请提供更好的解决方案.

解决方法

无需担心在ORDER BY表达式中指定常量.以下内容引自Itzik Ben-Gan撰写的 Microsoft SQL Server 2012 High-Performance T-SQL Using Window Functions(可从Microsoft免费电子书网站免费下载):

As mentioned,a window order clause is mandatory,and SQL Server
doesn’t allow the ordering to be based on a constant—for example,
ORDER BY NULL. But surprisingly,when passing an expression based on a
subquery that returns a constant—for example,ORDER BY (SELECT
NULL)—SQL Server will accept it. At the same time,the optimizer
un-nests,or expands,the expression and realizes that the ordering is
the same for all rows. Therefore,it removes the ordering requirement
from the input data. Here’s a complete query demonstrating this
technique:

SELECT actid,tranid,val,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS rownum
FROM dbo.Transactions;

Observe in the properties of the Index Scan iterator that the Ordered
property is False,meaning that the iterator is not required to return
the data in index key order

以上意味着当您使用常量排序时不会执行.我强烈建议您阅读本书,因为Itzik Ben-Gan深入介绍了窗口功能的工作原理以及如何在使用时优化各种情况.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读