问一个简单的关于 in 和 not in 的问题,快来抢分.
有两个表结构一样的表   table1,table2. 
 现在要将   table2中的数据插入到table1中,而table2中的数据部分数据已经存在table1中了.      现在我只能判断其中的字段   cardID   (里面保存的是身份证号码)来判断数据是否已经在   table1中. 
 select   *   from   table2            --有一万多条数据 
 select   *   from   table2   where   cardID   in   (select   cardID   from   table1)   --350条数据 
 select   *   from   table2   where   cardID   not   in   (select   cardID   from   table1)      --没有数据.(这个按照我原来的判断,认为会出现   一万条减去350条才对)   
 请问各位,怎么样才能靠判断   字段cardID是否重复,把数据导入到table1中呢? 
 谢谢各位了!
------解决方案--------------------try:   
 select * from table2 t where not exists(select 1 from table1 where cardID=t.cardID)
------解决方案--------------------另外,如果 table2 的 cardID 为 null 时,会出现楼主描述的情况。
------解决方案----------------------确定cardID 为表的主键..   
 insert into table2 
 select * from table1 a where not exists (select 1 from table2 where cardID=a.table1)
------解决方案--------------------declare @t1 table(ID int,code varchar(6)) 
 declare @t2 table(ID int,code varchar(6))   
 insert into @t1 select 1, 'AAAA ' union select 2, 'BBBB ' union select 3, 'CCCC ' 
 insert into @t2 select 1, 'AAAA ' union select 3, 'BBBB ' union select null, 'CCCC '   
 select * from @t2 where ID in (select ID from @t1)  
 /* 
 ID          code    
 ----------- ------  
 1           AAAA 
 3           BBBB 
 */   
 select * from @t2 where ID not in (select ID from @t1) 
 /* 
 ID          code    
 ----------- ------  
 */
------解决方案--------------------请问各位,怎么样才能靠判断 字段cardID是否重复,把数据导入到table1中呢? 
 -------- 
 Insert table1 
 Select * From table2 
 Where Not Exists (Select cardID From table1 Where cardID = table2.cardID)
------解决方案----------------------那是因为cardID可能为空值,改成这样试试   
 select * from table2 a where exists (select 1 from table1 where a.cardID = cardID)  
 select * from table2 a where not exists (select 1 from table1 where a.cardID = cardID)
------解决方案--------------------怎么来抢分阿? 
 我不懂哦.?   
 最好使用 exists
------解决方案--------------------用not exists()可以解决这个问题:   
 declare @t1 table(ID int,code varchar(6)) 
 declare @t2 table(ID int,code varchar(6))   
 insert into @t1 select 1, 'AAAA ' union select 2, 'BBBB ' union select 3, 'CCCC ' 
 insert into @t2 select 1, 'AAAA ' union select 3, 'BBBB ' union select null, 'CCCC '   
 select * from @t2 t where not exists(select 1 from @t1 where ID=t.ID)   
 /* 
 ID          code    
 ----------- ------  
 NULL        CCCC 
 */
------解决方案----------------------邹老大的。 
 --1. NULL 对 IN(NOT IN) 查询的影响 
 --测试数据 
 DECLARE @1 TABLE(col1 int) 
 INSERT @1 SELECT 1 
 UNION ALL SELECT NULL 
 UNION ALL SELECT 2   
 DECLARE @2 TABLE(col1 int) 
 INSERT @2 SELECT 1   
 --查询 
 SELECT [@1总记录数]=COUNT(*) FROM @1 
 --结果: 3   
 SELECT [@1在@2表中存在的记录数]=COUNT(*) FROM @1 a 
 WHERE col1 IN(SELECT col1 FROM @2)