恩这样:
对于一个有主键的表进行查询,
查询结果,因该是按照 主键进行排序的 
比如
id
1
2
3
10
11
20但是使用in 这样的子查询以后.
结果变成了
1
10
11
2
20
3
是什么原因?
我这样表述,不知道清楚与否 ?

解决方案 »

  1.   

    your query do not have order by, the order of the result is not always sorted, even you have the Primary key
    adding order by clause
      

  2.   

    楼上的意思是,我使用in查询导致不使用主键排序了.我可以理解为,语句里有in时,排序就按照上面的方式进行排序了么 ?
      

  3.   

    E文的牛!我给你专门做了个测试:
    create table a 
    (
    id int  CONSTRAINT PK_a_id PRIMARY KEY NONCLUSTERED,
    name varchar(10)
    )
    -- drop table a 
    insert into a select 1 ,'a'
    union all select 3,'a'
    union all select 4,'d'
    union all select 14,'a'
    union all select 42,'a'
    union all select 25,'a'
    union all select 31,'b'
    union all select 30,'b'
    union all select 10,'a'
    union all select 11,'c'
    union all select 12,'a'
    union all select 21,'a'
    union all select 23,'a'select * 
    from  a 
    where id in (select id from a where name in ('a','c'))
    id          name       
    ----------- ---------- 
    1           a
    3           a
    14          a
    42          a
    25          a
    10          a
    11          c
    12          a
    21          a
    23          a(所影响的行数为 10 行)select * 
    from  a 
    id          name       
    ----------- ---------- 
    1           a
    3           a
    4           d
    14          a
    42          a
    25          a
    31          b
    30          b
    10          a
    11          c
    12          a
    21          a
    23          a(所影响的行数为 13 行)
    ---
    我的结论是:
    主键与排序无关,除非你有索引
      

  4.   

    IN 的作用相当与OR
      
      语句:
      
      Select * from table1 where tid in (2,3)
      
      和
      
      Select * from table1 where tid=2 or tid=3
      是一样的,都会引起全表扫描,如果tid上有索引,其索引也会失效。使用in的时候 索引也无效了,这时排序按照什么来排 呢 ?对排序是否有效?
      

  5.   

    自己找到结果了:
    说明一下:
    结果的排序和in的执行过程有关系
    Select * from table1 where tid in (2,3)先会执行括号中的子查询,用结果和 in之前的字段进行对比 ,如果匹配返回true,并把该
    条记录插入到主查询的结果表中,开始处理下一条记录。我问的问题 ,因为在 子查询中使用了 order by 这样的排序,所以结果也是混乱的。