Die*_*ego 4 sql t-sql sql-server sql-server-2005 sql-server-2008
你知道什么时候你有这么大的日志表,你只需要查看最后的X行,知道当时发生了什么?
通常你可以这样做:
select top 100 *
from log_table
order by ID desc
Run Code Online (Sandbox Code Playgroud)
显示100个最新记录,但它将按逆序(当然,因为DESC的顺序),例如:
100010
100009
100008
and so on..
Run Code Online (Sandbox Code Playgroud)
但为了简单起见,我希望看到他们发生的订单记录.我可以通过运行此查询来做到这一点:
select *
from(
select top 100 * from log_table order by ID desc
) a
order by a.id
Run Code Online (Sandbox Code Playgroud)
我通过ID desc得到我的前100个订单,然后反转结果集.它工作但似乎没有必要运行2选择产生这个结果.
我的问题是:有没有人有更好的想法呢?就像桌子末尾的精选顶部一样?
编辑:两个查询的执行计划:似乎亚历克斯的想法非常好,但大卫也是对的,只有一个选择和一种

EDIT2:设置统计IO ON:
(10 row(s) affected)
Table 'sysdtslog90'. Scan count 1, logical reads 3, physical reads 0, read-ahead reads 0, lob logical reads 12, lob physical reads 0, lob read-ahead reads 0.
(1 row(s) affected)
(10 row(s) affected)
Table 'sysdtslog90'. Scan count 2, logical reads 5, physical reads 0, read-ahead reads 0, lob logical reads 12, lob physical reads 0, lob read-ahead reads 0.
(1 row(s) affected)
Run Code Online (Sandbox Code Playgroud)
但似乎没必要运行2选择产生这个结果.
错误.有必要.
更多详细信息:查看查询的估计执行计划.它可能看起来像ClusteredIndexScan - > Top - >只有一个Sort.内部查询的OrderBy不执行排序,它只是指示执行从表的"后面"读取.
| 归档时间: |
|
| 查看次数: |
1186 次 |
| 最近记录: |