Home > Database > Mysql Tutorial > body text

oracle中 exists 与 in效率及其用法

WBOY
Release: 2016-06-07 17:45:50
Original
1235 people have browsed it

oracle中 exists 与 in效率及其用法

用not exists 代替not in

* from tsp_product p where not exists(select '' from tsp_orderitem i where p.id=i.product_id)
select * from tsp_product p where id not in(select product_id from tsp_orderitem i where p.id=i.product_id)
用exists 代替in
select * from tsp_product p where p.id  in(select product_id from tsp_orderitem )
select * from tsp_product p where  exists(select 'x' from tsp_orderitem i where p.id =i.product_id )

下面来分析为什么用用not exists 代替not in

有两个简单例子,以说明 “exists”和“in”的效率问题

1) select * from t1 where exists(select 1 from t2 where t1.a=t2.a) ;

    t1数据量小而t2数据量非常大时,t1

2) select * from t1 where t1.a in (select t2.a from t2) ;

     t1数据量非常大而t2数据量小时,t1>>t2 时,2) 的查询效率高。

 

union
把两张表的数据合起来,如有重复行,只取一行
union all
把两张表的数据合起来,不过滤重复行
minus
返回在第一个查询结果中与第二个查询结果不相同的那部分行记录。 

oracle有这样的一些约定
1.select语句必须返回相同的列数,如果列数不同的话,可以选择串代替列。
2.select语句中相应的列必须有相同的数据类型,长度可以不同

rollup

统计:select sum(s.totalamount),to_char(createdate,'yyyy-mm') from tsp_orders s group by rollup(to_char(createdate,'yyyy-mm')

connect by
select level,a. * from tsp_area a start with parent_id is null connect by prior id = parent_id


说明:创建类似树报表。
 prior 强制报表的顺序变为从根到叶(如果prior是父辈)或从叶到根(如果prior是后代)
 虽然where子句可以人树排除上体,但无法排除他们的子孙子(或者祖先,如果prior在等号的右边)


详细看看它他的区别

exists 用法:

请注意 1)句中的有颜色字体的部分 ,理解其含义;

其中 “select 1 from t2 where t1.a=t2.a” 相当于一个关联表查询,相当于

“select 1 from t1,t2     where t1.a=t2.a”

但是,如果你当当执行 1) 句括号里的语句,是会报语法错误的,这也是使用exists需要注意的地方。

“exists(xxx)”就表示括号里的语句能不能查出记录,它要查的记录是否存在。

因此“select 1”这里的 “1”其实是无关紧要的,换成“*”也没问题,它只在乎括号里的数据能不能查找出来,是否存在这样的记录,如果存在,这 1) 句的where 条件成立。


in 的用法:

继续引用上面的例子

“2) select * from t1 where t1.a in (select t2.a from t2) ”

这里的“in”后面括号里的语句搜索出来的字段的内容一定要相对应,一般来说,t1和t2这两个表的a字段表达的意义应该是一样的,否则这样查没什么意义。

打个比方:t1,t2表都有一个字段,表示工单号,但是t1表示工单号的字段名叫“ticketid”,t2则为“id”,但是其表达的意义是一样的,而且数据格式也是一样的。这时,用 2)的写法就可以这样:

“select * from t1 where t1.ticketid in (select t2.id from t2) ”

select name from employee where name not in (select name from student);

select name from employee where not exists (select name from student);

 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!