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=latin1CREATE 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