sql – 没有ORDER BY的ROW_NUMBER

前端之家收集整理的这篇文章主要介绍了sql – 没有ORDER BY的ROW_NUMBER前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我要在现有查询添加行号,以便我可以跟踪已添加到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深入介绍了窗口功能的工作原理以及如何在使用时优化各种情况.

原文链接:https://www.f2er.com/mssql/78153.html

猜你在找的MsSQL相关文章