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, `name` varchar(255) 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, category_id, htmlfile, title, convert(varchar(20),begintime,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
exists表示()内子查询语句返回结果不为空说明where条件成立就会执行主sql语句,如果为空就表示where条件不成立,sql语句就不会执行。
not exists和exists相反,子查询语句结果为空,则表示where条件成立,执行sql语句。负责不执行。
select nvl(count(distinct o.member_id), 0) as newMembers from order_info o, member mb where o.member_id = mb.member_id and o.is_delete = 'N' and mb.is_delete = 'N' and not exists (select oi.member_id from order_info oi, member mb where oi.is_delete = 'N' /*有效订单条件*/ and (oi.audit_time is not null and oi.order_state NOT in (18, 19, 25)) and oi.member_id = mb.member_id)
select oi.member_id
from order_info oi, member mb
where oi.is_delete = 'N'
/*有效订单条件*/
and (oi.audit_time is not null and
oi.order_state NOT in (18, 19, 25))
and oi.member_id = mb.member_id
这条sql是有数据的,所以not exists 在执行的时候,是没数据的,exists是有数据的
https://www.iteye.com/blog/yangzhonglei-699673