日期:2014-05-19  浏览次数:20577 次

两条sql语句的效率问题,高手进
有两个表
表1:info(信息表)   有id(编号),title(标题),addtime(发布时间)   等字段
表2:prop(栏目表)   有infoid(信息标号),intprop(所属栏目编号)   等字段
注:一条信息可同时属于1个或1个以上栏目  

现在我要查   栏目编号为5的所有信息
下面两条语句可查出:
语句1:select   distinct   a.id,a.title,a.addtime   from   info   as   a   inner   join   prop   as   b
on   a.id=b.infoid   and   b.intprop=5   order   by   a.addtime   desc

语句2:select   a.id,a.title,a.addtime   from   info   as   a  
where   exists(select   infoid   from   prop   as   b   where   b.infoid   =a.id   and   b.intprop=5)  
order   by   a.addtime   desc

经测试,语句2的效率要比语句1高.
大家讨论下,语句2的效率为什么会比语句1高.语句2这样的写法会不会引起死锁,有没有什么弊端?
谢谢!!

------解决方案--------------------
exists比较好,因为它只进行 "存在 "测试
------解决方案--------------------
去掉distinct应该是一样的效率

说说prop 表的索引

------解决方案--------------------
使用exists只是比判断有没有这条数据,有就执行没有就下一条,
不需要去做连接,不会产生笛卡尔集
所以速度就快
------解决方案--------------------
我觉得是第一种效率高一些吧

exists虽然是只进行存在判断,但是必须要逐条执行吧

如果info表的数量大的话,效率应该会很低

------解决方案--------------------
a表98w条数据,b表92w条数据,结果集有1千条数据左右

测试结果,
两条语句的执行时间都在0.8秒左右,几乎没有差别

不过第二种写法这样写会更好一点点

select a.id,a.title,a.addtime from info as a
where exists(select 1 from prop as b where b.infoid =a.id and b.intprop=5)
order by a.addtime desc