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

求一个算法,查询一个表的记录在另一个表中不重复存在的记录.
在一个表red(qs,r1,r2,r3,r4,r5,r6)里面有上千条数据.
另一个表fanwei(xh,f1,f2,f3,f4,f5,f6)里面有30万条数据.
字段全部数值型.
结构基本相同.
要求:如果fanwei的f1到f6与red的r1到r6有n(n <=6)个以上的数字相同,则将其删除.
说明:
1.每个数据行(r1到r6,f1-f6)数字是由小到大的,不重复.
2.r1等于f1到f6中任意一个数字也算一个数字相同.r2,r3,r4,r5,r6同理.
由于本人算法太笨.写好的程序运行了2个小时才完成删除操作.
求一个最快的算法.



------解决方案--------------------
--不知道跑這個要不要2個小時,也不知道邏輯對不對^^

declare @n int
set @n=? --匹配相同的數目

declare @qs int,@r1 int,@r2 int,@r3 int,@r4 int,@r5 int,@r6 int
declare c1 cursor for
select * from red
open c1
fetch next from c1 into @qs,@r1,@r2,@r3,@r4,@r5,@r6
while @@fetch_status=0
begin
delete fanwei
where case when charindex( ', '+rtrim(@r1)+ ', ', ', '+rtrim(f1)+ ', '+rtrim(f2)+ ', '+rtrim(f3)+ ', '+rtrim(f4)+ ', '+rtrim(f5)+ ', '+rtrim(f6)+ ', ')> 0 then 1 else 0 end
+case when charindex( ', '+rtrim(@r2)+ ', ', ', '+rtrim(f1)+ ', '+rtrim(f2)+ ', '+rtrim(f3)+ ', '+rtrim(f4)+ ', '+rtrim(f5)+ ', '+rtrim(f6)+ ', ')> 0 then 1 else 0 end
+case when charindex( ', '+rtrim(@r3)+ ', ', ', '+rtrim(f1)+ ', '+rtrim(f2)+ ', '+rtrim(f3)+ ', '+rtrim(f4)+ ', '+rtrim(f5)+ ', '+rtrim(f6)+ ', ')> 0 then 1 else 0 end
+case when charindex( ', '+rtrim(@r4)+ ', ', ', '+rtrim(f1)+ ', '+rtrim(f2)+ ', '+rtrim(f3)+ ', '+rtrim(f4)+ ', '+rtrim(f5)+ ', '+rtrim(f6)+ ', ')> 0 then 1 else 0 end
+case when charindex( ', '+rtrim(@r5)+ ', ', ', '+rtrim(f1)+ ', '+rtrim(f2)+ ', '+rtrim(f3)+ ', '+rtrim(f4)+ ', '+rtrim(f5)+ ', '+rtrim(f6)+ ', ')> 0 then 1 else 0 end
+case when charindex( ', '+rtrim(@r6)+ ', ', ', '+rtrim(f1)+ ', '+rtrim(f2)+ ', '+rtrim(f3)+ ', '+rtrim(f4)+ ', '+rtrim(f5)+ ', '+rtrim(f6)+ ', ')> 0 then 1 else 0 end
= @n
end
close c1
deallocate c1
------解决方案--------------------
两个表之间有没有一定的对应关联,比如说qs和XH是不是有关联

如果两个表没有什么对应关联,那么一条条的对比方法:30万*上千条记录*6=近2000万计算,运行时间一定会很长


------解决方案--------------------
declare @n int
set @n=1 --匹配相同的數目

delete fanwei
from fanwei f
inner join red r
on f1 = f.f1 and f2 = f.f2 and f3 = f.f3 and f4 = f.f4 and f5 = f.f5 and f6 = f.f6
and case when charindex( ', '+rtrim(r.r1)+ ', ', ', '+rtrim(f.f1)+ ', '+rtrim(f.f2)+ ', '+rtrim(f.f3)+ ', '+rtrim(f.f4)+ ', '+rtrim(f.f5)+ ', '+rtrim(f.f6)+ ', ')> 0 then 1 else 0 end
+case when charindex( ', '+rtrim(r.r2)+ ', ', ', '+rtrim(f.f1)+ ', '+rtrim(f.f2)+ ', '+rtrim(f.f3)+ ', '+rtrim(f.f4)+ ', '+rtrim(f.f5)+ ', '+rtrim(f.f6)+ ', ')> 0 then 1 else 0 end
+case when charindex( ', '+rtrim(r.r3)+ ', ', ', '+rtrim(f.f1)+ ', '+rtrim(f.f2)+ ', '+rtrim(f.f3)+ ', '+rtrim(f.f4)+ ', '+rtrim(f.f5)+ ', '+rtrim(f.f6)+ ', ')> 0 then 1 else 0 end
+case when charindex( ', '+rtrim(r.r4)+ ', ', ', '+rtrim(f.f1)+ ', '+rtrim(f.f2)+ ', '+rtrim(f.f3)+ ', '+rtrim(f.f4)+ ', '+rtrim(f.f5)+ ', '+rtrim(f.f6)+ &