sql - 反向选择 TOP *

标签 sql sql-server sql-server-2008 tsql sql-server-2005

你知道什么时候你有那么大的日志表,你只需要查看最后 X 行就知道当时发生了什么吗?

通常你可以这样做:

select top 100 * 
from log_table
order by ID desc

显示最新的100条记录,但是是倒序的(当然是因为按DESC排序),例如:

100010
100009
100008
and so on..

但为了简单起见,我想查看它们发生的顺序的记录。 我可以通过运行以下查询来做到这一点:

select * 
from(
    select top 100 * from log_table order by ID desc
    ) a
order by a.id

我通过 ID desc 获取前 100 个订单,然后反转结果集。 它有效,但似乎没有必要运行 2 select 来产生这个结果。

我的问题是:有人有更好的主意吗?就像表格末尾的选择顶部一样?

编辑: 两个查询的执行计划: 看来Alex的想法很好,但David也是对的,只有一种选择和一种排序 enter image description here

编辑2: 设置统计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)

最佳答案

but it seems kin of unnecessary to run 2 select to produce this result.

错了。这是必要的。

更多详细信息:查看查询的估计执行计划。它可能看起来像 ClusteredIndexScan -> Top -> 只有一种排序。内部查询的 OrderBy 不执行排序,它只是指示执行从表的“后面”读取。

关于sql - 反向选择 TOP *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10739523/

相关文章:

sql - 根据多值参数中断 SSRS 报告

sql - 编写动态 SQL 函数

sql - 使用 IF..ELSE IF 控制 T-SQL SP 中的流程 - 还有其他方法吗?

sql - 使用一个 int 列表进行多次插入

sql - 在触发器执行之前数据库关闭会发生什么?

mysql - SQL - 缩短查询

php - Sql 在 codeigniter 中将 AND 与 OR 组合

java - 从 Java 1.4 连接到 SQL 2008

mysql - 如何将两列连接到同一个表

sql - 如何在 Postgres 的不同行中连接字符串