create table test1(ID int,ParentID int,TestField varchar(10))
insert into test1 select 1,0,'aaa'
insert into test1 select 2,1,'bbb'
insert into test1 select 3,1,'ccc'create table test2(ID int,ParentID int,TestField varchar(10))
insert into test2 select 1,0,'aaa'
insert into test2 select 2,1,'bbb'
insert into test2 select 3,1,'ccc'
insert into test2 select 4,3,'ddd'
insert into test2 select 5,3,'eee'
insert into test2 select 6,0,'fff'select test1.*,test2.* from test1,test2
where test1.id<>test2.id
执行结果是返回15条记录,因为是笛卡尔乘积.但是执行
select a.* from test2 a
where  exists (select * from test1 where a.id<>id)
返回的是test2表中所有的记录
1 0 aaa
2 1 bbb
3 1 ccc
4 3 ddd
5 3 eee
6 0 fff
为什么?如果在where 查询条件中有个子查询,那么子查询中的表和主查询中的表是怎么联结的?
为什么第二条语句执行之后不是返回3条记录?

解决方案 »

  1.   

    select a.* from test2 a
    where  exists (select * from test1 where a.id<>id)
    查詢test2每條紀錄時,都會到test1中查詢是否有不等於當前id的紀錄,每條紀錄都滿足條件,
    所以查詢出來是所有紀錄。
      

  2.   

    select * from test2 a where not exists(select 1 from test1 where id=a.id)
      

  3.   

    orselect * from test2 a where id not in(select id from test1)我觉得还是你写的那个exists有问题
      

  4.   

    楼上:
    我原来就是select * from test2 a where not exists(select 1 from test1 where id=a.id)这么写的,但就是没明白为什么不能select a.* from test2 a where  exists (select * from test1 where a.id<>id)这么写
      

  5.   

    select a.* from test2 a where  exists (select * from test1 where a.id<>id)
    ---------
    语句执行是这样的,要知道exists原理是按行进行搜索的,每执行一行,判断exists是true或是false,如果为false就不输出结果,如果true就输出结果,所以在扫描test2的id=1的时候,执行子查询select * from test1 where 1<>id,这一句有返回结果,所以为true,同理,id=2,3的时候,也返回true,最后应该是test2的所有记录,我想这样你应该清楚了吧~
      

  6.   

    假設現在是第一條紀錄
    1 0 aaa
    到test1中判斷有沒有id不等於1的紀錄,有,所以是這條紀錄是滿足條件的。
    然後第二條紀錄
    2 1 bbb
    到test1中判斷有沒有id不等於2的紀錄,有,所以是這條紀錄是滿足條件的。
    ...test2中所有紀錄都滿足條件,所以所有紀錄都查詢出來了。