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

求一条高效查询语句写法
有两张表,表结构一模一样
adshowlog
adid,ip,numiid,adtime,uid

adshowlog2
adid,ip,numiid,adtime,uid

想查询adshowlog2中的uid,查询条件是:adshowlog2中的ip、numiid不出现在adshowlog中

拜谢大虾

------解决方案--------------------
SQL code

--uid和IP和numiid有一项不相同的

select * from adshowlog2 as a where not exists(select 1 from dshowlog where uid=a.uid and ip=a.ip and numiid=a.numiid)
--uid存在,IP和numiid有一项不相同
select * from adshowlog2 as a where not exists(select 1 from dshowlog where uid=a.uid and ip=a.ip and numiid=a.numiid)
and exists(select 1 from dshowlog where uid=a.uid)

------解决方案--------------------
SQL code

select a2.uip
from adshowlog a, adshowlog2 a2
where a.ip <> a2.ip
and a.numidd <> a2.numidd

------解决方案--------------------
这样就行了
SQL code
select * from adshowlog2 as a where not exists(select 1 from dshowlog where  ip=a.ip and numiid=a.numiid)

------解决方案--------------------
要查询不存在,一想就是not exists
大版的正解
------解决方案--------------------
SQL code

select * from adshowlog2 as a where not exists(select 1 from dshowlog where  ip=a.ip and numiid=a.numiid)

------解决方案--------------------
使用相关子查询和not exists
------解决方案--------------------
exists的查询过程 ,只要有一条查询结果,则终止该次查询,执行下一次查询
------解决方案--------------------
用左连接,去掉null
探讨

楼上说的这点我也看到了,就是数据多的时候还是比较慢。
我那种写法就怕逻辑不对,速度还是不慢的。我用的是mysql
join on 应该可以带and条件的吧?

------解决方案--------------------
探讨
查询不存在,用not exists效率到底算不算高?
adshowlog数据有40万条左右
adshowlog2数据只有几千
用not exists运行要160秒左右。
而我用下面这样的语句不知道对不对,反正执行效率蛮高的,10秒左右搞定,ip和numiid都有索引的
ps:我用的是.net连接的mysql数据库,发到mssql版来了。我的语句如下,不知道逻辑对不对

SQL cod……

------解决方案--------------------
select * from adshowlog2 as a where not exists(select 1 from dshowlog where ip=a.ip and numiid=a.numiid)

------解决方案--------------------
select a2.*
from adshowlog2 a2
left join adshowlog a1 on a1.ip = a2.ip and a1.numiid = a2.numiid
where a.adid is null