日期:2014-05-19  浏览次数:20451 次

遇到难题了,是查询分析器的错还是我的错?
大家先不要管这两条查询语句的业务逻辑是什么,就看这两条语句为什么会返回不同的结果?
两条语句对应的exists完全相同,在我看来这两条语句是等价的呀。
--创建测试环境
create   table   #t1(编号   int,部门   varchar(10),日期1   datetime,状态   bit)
create   table   #t2(编号   int,部门   varchar(10),日期2   datetime,状态   bit)
create   table   #t3(编号   int,部门   varchar(10),日期   datetime)

--插入测试数据
insert   #t1(编号,部门,日期1,状态)
select   '10001 ', '01 ', '2007-02-02 ', '0 '   union   all
select   '10002 ', '01 ', '2007-02-06 ', '0 '   union   all
select   '10003 ', '02 ', '2007-02-01 ', '0 '   union   all
select   '10006 ', '02 ', '2007-03-02 ', '0 '   union   all
select   '10001 ', '03 ', '2007-03-01 ', '0 '   union   all
select   '10005 ', '03 ', '2007-03-01 ', '0 '

insert   #t2(编号,部门,日期2,状态)
select   '10003 ', '02 ', '2007-02-10 ', '1 '

insert   #t3(编号,部门,日期)
select   '10001 ', '01 ', '2007-02-03 '   union   all
select   '10002 ', '01 ', '2007-02-10 '   union   all
select   '10003 ', '02 ', '2007-02-06 '   union   all
select   '10006 ', '02 ', '2007-03-02 '   union   all
select   '10001 ', '03 ', '2007-03-01 '   union   all
select   '10005 ', '03 ', '2007-02-22 '   union   all
select   '10005 ', '03 ', '2007-03-02 '

--求解过程1
select   *
from   #t3   t3
where   exists(
            select   1  
            from   #t1   t1  
            where   not   exists--如果表1中有2个以上相同编号则以日期1最大的为条件  
                                    (select   1   from   #t1   where   编号   =   t1.编号   and   日期1   >   t1.日期1)
                        and   t3.编号   =   t1.编号   and   t3.部门   =   t1.部门--表3中的编号和部门同时存在表1中
                        and   not   exists--表3中的编号和部门同时表2中不存在
                                    (select   1   from   #t2   where   编号   =   t1.编号   and   部门   =   t1.部门)
            )
           
union   all

select   *
from   #t3   t3
where   exists(
            select   1  
            from   #t1   t1  
            where   not   exists--如果表1中有2个以上相同编号则以日期1最大的为条件