数据库sql语句的exists总结
数据库sql语句的exists总结 sql exists in 学习
?
先来比较下语法:
--deals=交易表,areas=地域表,例如香港;我们的目的:查看有交易的地域
select * from areas where id in (select city_id from deals);
select * from areas where?id?in? ?(select city_id from deals?where deals.city_id = areas.id);
select * from areas where exists (select null ? ? from deals where deals.city_id = areas.id);
区别:
EXISTS语法并没有说哪个字段落在了子查寻的结果中,而是说exists后面的语句执行的结果是不是有记录,只要有记录,则主查询语句就成立。它代表‘存在’,用来引领嵌套查询的子查询,它不返回任何数据,只产生逻辑真值‘true’与逻辑假值‘False’。由EXISTS引出的子查询,其目标列表达式通常都用*(用null也可以),因为带有EXISTS的子查询只返回真值或假值,给出列名没有实际意义。
?
性能变化的关键:#1 执行的先后顺序谁是驱动表,谁先执行查询,谁后执行查询#2 执行过程exists的优点是:只要存在就返回了,这样的话很有可能不需要扫描整个表。 ?in需要扫描完整个表,并返回结果。所以,在字表比较小的情况下,扫描全表和部分表基本没有差别;但在大表情况下,exists就会有优势。看这两个语句:--子查询会执行完全关联,并返回所有符合条件的city_idselect * from areas where?id?in? ?(select city_id from deals?where deals.city_id = areas.id);
--子查询的关联其实是一样的,但子查询只要查到一个结果,就返回了,所以效率还是比较高些的
?
select * from areas where?exists?(select null ? ? from deals where deals.city_id = areas.id);
#3 字表查询的结果exists判断子查询的结果是不是存在,但查到什么结果,什么字段,并不关心;in ? ? ?需要子查询查得的结果给主查询使用?
、用exists替代in(发现好多程序员不知道这个怎么用):?在许多基于基础表的查询中,为了满足一个条件,往往需要对另一个表进行联接。?
在这种情况下,使用exists(或not exists)通常将提高查询的效率。?
举例:?
(低效)?
select ... from table1 t1 where t1.id > 10 and pno in (select no from table2 where name like 'www%');?
(高效)?
select ... from table1 t1 where t1.id > 10 and exists (select 1 from table2 t2 where t1.pno = t2.no and name like 'www%');?
10、用not exists替代not in:?
在子查询中,not in子句将执行一个内部的排序和合并。?
无论在哪种情况下,not in都是最低效的 (因为它对子查询中的表执行了一个全表遍历)。?
为了避免使用not in,我们可以把它改写成外连接(Outer Joins)或not exists。?
11、用exists替换distinct:?
当提交一个包含一对多表信息的查询时,避免在select子句中使用distinct. 一般可以考虑用exists替换?
举例:?
(低效)?
select distinct d.dept_no, d.dept_name from t_dept d, t_emp e where d.dept_no = e.dept_no;?
(高效)?
select d.dept_no, d.dept_name from t_dept d where exists (select 1 from t_emp where d.dept_no = e.dept_no);?
exists使查询更为迅速,因为RDBMS核心模块将在子查询的条件一旦满足后,立刻返回结果.?
12、用表连接替换exists:?
通常来说,采用表连接的方式比exists更有效率。?
举例:?
(低效)?
select ename from emp e where exists (select 1 from dept where dept_no = e.dept_no and dept_cat = 'W');?
SELECT ENAME?
(高效)?
select ename from dept d, emp e where e.dept_no = d.dept_no and dept_cat = 'W';
?
?
R
R
R
+R
R
R