这两句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
请问这两句中哪个效率会高一点?还有没有更好的写法?
自己测试了一下。效果很明显。第二句sql要比前一句效率高很多。
放到数据库里执行一下,看一下时间不就行了
先把第一次查询到的结果集放到一个临时表变量,这样写感觉很乱
都不高吧?
那你有什么好办法吗?
@Al-one: 看不懂,不好意思。感觉嵌套了很多。至于瓶颈在哪里,看看sql的执行过程,看看微软给的建议。