首页 新闻 赞助 找找看

我想知道这两句SQL的效率怎么样?

0
悬赏园豆:10 [已解决问题] 解决于 2014-03-27 11:31

这两句SQL的目标是想要查询一些栏目class,同时查出栏目下的第一条信息info,以及每个栏目下的信息条数。

select c.*,i.id as i_id,i.i_name,t.c_info_count
from (class c
left join info i on i.i_cid = c.id)
left join (
  select i_cid,count(id) as c_info_count from info group by i_cid
) t on t.i_cid = c.id
where c.c_pid = 0
and (
  i.id = (
    select top 1 id from info where i_cid = c.id order by id desc
  ) or i.id is null
)

后来我改成了:

select c.*,i.id as i_id,i.i_name,t.c_info_count
from (class c
left join (
  select i3.* from (
    select i_cid,max(id) as i_id_max
    from info group by i_cid) i2
    left join info i3 on i3.id = i2.i_id_max
  ) i on i.i_cid = c.id
)
left join (
  select i_cid,count(id) as c_info_count from info group by i_cid
) t on t.i_cid = c.id
where c.c_pid = 0

请问这两句中哪个效率会高一点?还有没有更好的写法?

Al-one的主页 Al-one | 菜鸟二级 | 园豆:227
提问于:2014-03-24 13:42
< >
分享
最佳答案
0

自己测试了一下。效果很明显。第二句sql要比前一句效率高很多。

Al-one | 菜鸟二级 |园豆:227 | 2014-03-27 11:29
其他回答(3)
0

放到数据库里执行一下,看一下时间不就行了

收获园豆:10
最长的路漫漫 | 园豆:252 (菜鸟二级) | 2014-03-24 14:15
0

先把第一次查询到的结果集放到一个临时表变量,这样写感觉很乱

royalwong_real | 园豆:136 (初学一级) | 2014-03-24 16:17
0

都不高吧?

lucika.zh | 园豆:62 (初学一级) | 2014-03-26 08:42

那你有什么好办法吗?

支持(0) 反对(0) Al-one | 园豆:227 (菜鸟二级) | 2014-03-26 13:36

@Al-one: 看不懂,不好意思。感觉嵌套了很多。至于瓶颈在哪里,看看sql的执行过程,看看微软给的建议。

支持(0) 反对(0) lucika.zh | 园豆:62 (初学一级) | 2014-03-26 15:43
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册