zoukankan      html  css  js  c++  java
  • top未加order by,结果出错

    1、查询第21-30条记录

    select top 10 * from sys_Module where ID >
    (
    select max(ID) from (select top 20 * from sys_Module ) as a
    )

    查询结果:什么也 没有

    1.1 执行 select max(ID) from (select top 20 * from sys_Module ) as a 发现结果为46(数据库中记录共46条)

    1.2 执行select top 20 * from sys_Module,结果正确就是1-20的记录

    为什么和在一起就不对了

    原因:出现在from子句中的表我们称为派生表。派生表是虚拟的,未被物理具体化,也就是说当编译的时候,外部查询和内部查询会被合并,并生成一个计划。

    select top 20 * from sys_Module 返回的是表sys_Module,select max(ID)从表sys_Module里查询。

    2、正确方法

    select top 10 * from sys_Module where ID >
    (
    select max(ID) from (select top 20 * from sys_Module order by ID) as a
    )

    select top 20 * from sys_Module order by ID ,而order by返回的不是表而是游标,top可以从order by返回的游标里选择指定数量生成一个表并返回。

    select max(ID)从这个返回的表里查询。

  • 相关阅读:
    GO开发[一]:golang语言初探
    Python带参数的装饰器
    Python函数篇
    19. logging模块
    18. json模块
    17. os模块
    16. sys模块
    15. random模块
    14. 模块-time模块
    29. java面向对象项目
  • 原文地址:https://www.cnblogs.com/xiaochun126/p/4988877.html
Copyright © 2011-2022 走看看