首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

sql语句优化解决办法

2013-10-21 
sql语句优化我有这样一条sql语句: select t.* from t_cms_category t where t.id not in (selectt2.parent

sql语句优化
我有这样一条sql语句:
 select t.* from t_cms_category t where t.id not in (select  t2.parentid from t_cms_category t2);

表中的数据是:
SQL> select * from t_cms_category;
 
        ID NAME                                                                               PARENTID
---------- -------------------------------------------- ----------
     10001 test1                                                                                    -1
     10002 test2                                                                                    -1
     10003 test1.1                                                                               10001
     10004 test4                                                                                    -1
     10005 test2.1                                                                               10002

我希望得到的是1003 1004 1005 我上面写的sql能查出来 可是怎么优化下这条sql呢 求大神指点下
[解决办法]
 select t.* from t_cms_category t where t.id not in (select  t2.parentid from t_cms_category t2);



这么简单的语句理论上说是没啥可优化的,但是有一点要给你说一下,遇到楼主这种情况,可以选择两种过滤方式,一个是not in另一个是not exists,我理解不深,大概的用法就是左边比右边表记录多就用not in和in,右边表记录比左边多就用not exists和exists。我看着楼主的表结构逻辑上感觉应该是t_cms_category记录比(select t2.parentid from t_cms_category t2)的记录要少,所以是右边比左边记录多,应该用not exists比较快一点(数据量很大的时候才会明显)
select * from t_cms_category t where not exists (select 1 from t_cms_category where t.id = parentid)
楼主可以试试上面的语句,如果通过的话,应该在数据量大的时候很明显的感觉我的语句查询速度快。
[解决办法]

引用:
呵呵 我上网查了下优化了一下  select t1.* from t_cms_category t1 where not exists (select * from t_cms_category t2 where t2.id = t1.parentid);
我想问的是用exists或not exists的时候exists后面的语句是否一定要用关联表语句才OK因为我自己试……

not exists和exists里面的东西,必须要构成一个或真或假的条件才能起作用
其实用in还是exists取决于你的数据量,当in()里的数据量比较少的时候,使用in还是
比较合适的,如果数据量很大,上千上万的,建议用exists

热点排行