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

◣◣◣能否有高效一点的select语句,关于查询重复记录
已知两表结构相同,现在的情况是a,b表各有数据,f1和f2是组合关键字,用来确定记录的唯一性

a表
----------------------
f1     f2           v
11     aa           some   value
12     bb           some   body
13     hehe       haha


b表
------------------------
f1     f2           v
01     a             sm
02     b             sb
13     hehe       haha      

现在想做到把a表的这两条记录选出来
11     aa           some   value
12     bb           some   body
如何弄法


要求不要使用降低性能的group   by,及不要使用多重select子查询,最好用exist能提高性能的select语句

------解决方案--------------------
select * from a where not exists(select * from b where f1=a.f1 and f2=a.f2)
------解决方案--------------------
要求不要使用降低性能的group by,及不要使用多重select子查询,最好用exist能提高性能的select语句

NO,group by的速度快于exist,如F1、F2都是字符型
try:
select a.* from a left join b on a.f1+a.f2=b.f1+b.f2
where isnull(b.f1)
------解决方案--------------------
select a.* from a left join b on a.f1=b.f1 and a.f2=b.f2 where b.f1 is null
------解决方案--------------------
不是字符型也沒關係,這麼寫

Select A.* From A Left Join B On A.f1 = B.f1 And A.f2 = B.f2
Where B.f1 Is Null
------解决方案--------------------
select a.* from a left join b on a.f1+a.f2=b.f1+b.f2
where isnull(b.f1,0) <> 0
OR
select a.* from a left join b on a.f1+a.f2=b.f1+b.f2
where B.F1 is null

但是效率還得樓主測試下,不知道這裡的Left Join會不會影響效率。
应该不会,因为F1、F2是关键字

------解决方案--------------------
try:
select A.f1,A.f2 INTO #T FROM a表 AS A INNER JOIN b表 AS B ON A.f1=B.f1 AND A.f2=B.f2
SELECT * FROM a表 A WHERE EXISTS(SELECT 1 FROM #T AS B WHERE ON A.f1=B.f1 AND A.f2=B.f2)
DROP TABLE #T

对于数据量大的情况,这样的方法也可以考虑,理论上速度会提高很多,具体待测试。
------解决方案--------------------
我认为 还是用INNER JOIN 比较快。
无论左右关联 都会有null的数据 再加个id not null
效率不会多高。
(个人认为~~`)
------解决方案--------------------
> 1
select * from a where not exists(select * from b where f1=a.f1 and f2=a.f2)
> 2
select a.* from a left join b on a.f1=b.f1 and a.f2=b.f2 where b.f1 is null
> 3
select a.* from a left join b on a.f1+a.f2=b.f1+b.f2 where B.F1 is null
-----
2会快点,其次是3,1最慢

select A.f1,A.f2 INTO #T FROM a表 AS A INNER JOIN b表 AS B ON A.f1=B.f1 AND A.f2=B.f2
SELECT * FROM a表 A WHERE NOT EXISTS(SELECT 1 FROM #T AS B WHERE ON A.f1=B.f1 AND A.f2=B.f2)
DROP TABLE #T

------
效率不稳定,偶尔表现会快


Select A.* From A right join B On A.f1 = B.f1
Select A.* From A INNER JOIN B On A.f2 = B.f2
-----
偏题



------解决方案--------------------
> 1
select * from a where not exists(select * from b where f1=a.f1 and f2=a.f2)
------
select * from a where not exists(select 1 from b where f1=a.f1 and f2=a.f2)