日期:2014-05-18  浏览次数:20474 次

如何反查出不在当前表的全部数据?
有两个表:文件表A和文件文档关系表B

A数据:
fileId   fileName
1
2
3
4
5
6

B数据:
id   fileId   documentId
1     2
2     3
3     4
4     1

现在我想从A表中找出fileId不在B表的全部数据,从上面的例子看就是查出   5,6   这两条数据,我这样写SQL语句:
select   *   from   A   where   fileId   not   in   (
    select   fileId   from   B
)


但是在数据量大时这样的查询存在严重的效率问题,应该怎样写SQL语句??

谢谢:)

------解决方案--------------------
declare @A table(fileId int,fileName varchar(30))
insert into @A
select 1, ' '
union all select 2, ' '
union all select 3, ' '
union all select 4, ' '
union all select 5, ' '
union all select 6, ' '

declare @B table(id int,fileId int,documentId int)
insert into @B
select 1,2,0
union all select 2,3,0
union all select 3,4,0
union all select 4,1,0

select * from @A
select * from @B
select A.* from @A A left outer join @B B on A.fileId=B.fileId where B.id is null
------解决方案--------------------
做个left join
select *
from a left join b on a.id=b.id
where b.documentId is null