exists oracle 的用法

前端之家收集整理的这篇文章主要介绍了exists oracle 的用法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
CREATE TABLE `A` (
  `id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(255) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=latin1



CREATE TABLE `B` (
  `id` int(11) NOT NULL AUTO_INCREMENT,`AID` int(11) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=latin1
SELECT   ID,NAME   FROM   A   WHERE   EXISTS   (SELECT   1  FROM   B   WHERE   A.ID=B.AID) ;

结果为:

分享图片

 

表A和表B是1对多的关系   A.ID   =>   B.AID 

SELECT   ID,NAME   FROM   A   WHERE   EXIST   (SELECT   *   FROM   B   WHERE   A.ID=B.AID) 
执行结果为 
1       A1 
2       A2 
原因可以按照如下分析 
SELECT   ID,NAME   FROM   A   WHERE   EXISTS   (SELECT   *   FROM   B   WHERE   B.AID=1) 
---> SELECT   *   FROM   B   WHERE   B.AID=1有值,返回真,所以有数据

SELECT   ID,NAME   FROM   A   WHERE   EXISTS   (SELECT   *   FROM   B   WHERE   B.AID=2) 
---> SELECT   *   FROM   B   WHERE   B.AID=2有值,返回真,所以有数据

SELECT   ID,NAME   FROM   A   WHERE   EXISTS   (SELECT   *   FROM   B   WHERE   B.AID=3) 
---> SELECT   *   FROM   B   WHERE   B.AID=3无值,返回假,所以没有数据

NOT   EXISTS   就是反过来 
SELECT   ID,NAME   FROM   A   WHERE NOT   EXIST   (SELECT   *   FROM   B   WHERE   A.ID=B.AID) 
执行结果为 
3       A3 
=========================================================================== 
EXISTS   =   IN,意思相同不过语法上有点点区别,好像使用IN效率要差点,应该是不会执行索引的原因 
SELECT   ID,NAME   FROM   A    WHERE ID   IN   (SELECT   AID   FROM   B) 

NOT   EXISTS   =   NOT   IN  ,意思相同不过语法上有点点区别 
SELECT   ID,NAME   FROM   A   WHERE ID NOT   IN   (SELECT   AID   FROM   B)

 

=========================================================================== 
EXISTS:

系统要求进行sql优化,对效率比较低的sql进行优化,使其运行效率更高,其中要求对sql中的部分in/not in修改为exists/not exists

 

修改方法如下:

in的sql语句

SELECT id,category_id,htmlfile,title,convert(varchar(20),begintime,112) as pubtime 
FROM tab_oa_pub WHERE is_check=1 and 
category_id in (select id from tab_oa_pub_cate where no=‘1‘) 
order by begintime desc

修改为exists的sql语句SELECT id,112) as pubtime FROM tab_oa_pub WHERE is_check=1 and exists (select id from tab_oa_pub_cate where tab_oa_pub.category_id=convert(int,no) and no=‘1‘) order by begintime desc

猜你在找的Oracle相关文章