A表只有一列id,数据值连续的从1到100,第一个语句能查询到前10条记录,第二个语句本想查到id号为10的记录,执行后却显示了id为100的记录select * from (select top 10 * from A) as t 
select max(id) from (select top 10 * from A) as t 我认为第二条语句首先获得了前10条记录作为结果集,然后再从这个结果集中筛选出最大id号的记录.可是执行后结果却不是的,我想请教第二条语句为什么会是这样的结果,分析这条语句的工作机制?

解决方案 »

  1.   

    自动优化造成的
    Try
    select max(id) from (select top 10 * from A order by id) as t 
      

  2.   

    看来你的SQL有点问题,是不是没打补丁,安装过SP4没有(如果2000版本)
      

  3.   


    --这样写
    select max(id) from (select top 10 * from A order by ...) as t --用max的时候好像先默认对id排序了,然后执行里面的select top,
    --其实这个时候的结果跟 单独执行select top语句的结果不一样了
      

  4.   

    回5楼的:id是主键.
    我觉的4楼的解释可能是对的.
    还想问一下select max(id) from (select top 10 * from A) as t 在其它数据库中的显示结果如何,如MYSQL,如果不一样应该以谁为准?
      

  5.   

    select top 1 * from (select top 10 * from A order by id) as t order by id desc
    换个思路求最大行吗? 
      

  6.   

    在其它数据库中的显示结果如何,如MYSQL,如果不一样应该以谁为准?
    ----------------------------------
    这个没有以谁为准的 不同的数据库 即使使用完全相同的ANSI SQL 92标准语法 因为各自的编译存在差异 QUERY的结果也可能不同
      

  7.   

    不加Order by时候 看执行计划top进行了两次 应该是max的出现使得对表进行重排
      

  8.   

    试了一下,没加 order by 就是取最后一个id  (sp4 patch installed)
      

  9.   

    我的2005没问题 估计lz的sql有bug
      

  10.   

    create table t1 (id int primary key,name varchar(200),tele int)
    select 110,'aaa',600
    union all
    select 112,'aaa',700
    union all
    select 120,'aaa',500
    union all
    select 800,'aaa',400
    union all
    select 760,'aaa',200
    union all
    select 1,'aaa',100
    union all
    select 200,'sss',300
    union all
    select 150,'www',120
    union all
    select 400,'eee',180
    union all
    select 600,'eee',70

    1 字段上有索引
    select max(id) as id from (select top 3 * from t1) t
    select top 3 * from t1

    id
    600
    id name tele
    1 aaa 100
    150 www 120
    200 sss 3002 字段上无索引
    select max(tele) as tele from (select top 3 * from t1) t
    select top 3 * from t1

    tele
    300
    id name tele
    1 aaa 100
    150 www 120
    200 sss 300结论 top不带order by或索引提示,则按照表的聚集索引排序取数据,否则按照排序字段或索引排序例
    create index ix on t1(tele desc)则,对比
    select top 3 * from t1 with(index=ix)
    select top 3 * from t1
    select max(id) as id from (select top 3 * from t1 with(index=ix)) t
    select max(id) as id from (select top 3 * from t1 )t注:带有max操作的语句在执行前会先根据索引排序自己测试看,结果就不发了
      

  11.   

    回15楼的:根据你建的表
    查询select top 3 * from t1 结果不与你一样,我的是:id   name  tele
    1    aaa   100
    110  aaa   600
    112  aaa   700执行下面一句,结果为700,也与你的不一样select max(tele) as tele from (select top 3 * from t1) t 
    我用的是sql2000