您的位置:首页 > 数据库

关于SQL中exists和not exists的使用

2016-04-08 16:36 225 查看
1.建表,这里使用Oracle数据库,建表语句如下:

-- Create table
create table A
(
id   VARCHAR2(20),
name VARCHAR2(20)
)
tablespace USERS
pctfree 10
initrans 1
maxtrans 255
storage
(
initial 64K
minextents 1
maxextents unlimited
);
-- Create table
create table B
(
id   VARCHAR2(20),
aid  VARCHAR2(20),
name VARCHAR2(20)
)
tablespace USERS
pctfree 10
initrans 1
maxtrans 255
storage
(
initial 64K
minextents 1
maxextents unlimited
);


2.插入测试数据

insert into A (ID, NAME)
values ('1', 'A1');

insert into A (ID, NAME)
values ('2', 'A2');

insert into A (ID, NAME)
values ('3', 'A3');

insert into B (ID, AID, NAME)
values ('1', '1', 'B1');

insert into B (ID, AID, NAME)
values ('2', '2', 'B2');

insert into B (ID, AID, NAME)
values ('3', '2', 'B3');


3.创建SQL语句进行查询

--关于SQL中exists和not exists的使用
select id,name from A where exists(select * from B where A.ID=B.AID);
--结果如下:
--1	1	A1
--2	2	A2
--exists与in进行比较
select id,name from A where A.ID in(select B.AID from B);
--结果如下:
--1	1	A1
--2	2	A2
--分析exists的执行过程
select id,name from A where exists(select * from B where B.AID=1);
--结果如下:
--1	1	A1
--2	2	A2
--3	3	A3
select id,name from A where exists(select * from B where B.AID=2);
--结果如下:
--1	1	A1
--2	2	A2
--3	3	A3
select id,name from A where exists(select * from B where B.AID=3);
--结果如下:为空

--综上分析,应该是下面这种
select id,name from A where exists(select * from B where A.ID=1);
--结果如下:
--1	1	A1
select id,name from A where exists(select * from B where A.ID=2);
--结果如下:
--2	2	A2
select id,name from A where exists(select * from B where A.ID=3);
--结果如下:
--3	3	A3
--关于not exists的使用
select id,name from A where not exists(select * from B where A.ID=B.AID);
--3	3	A3
--与not in进行比较
select id,name from A where A.ID not in(select B.AID from B);
--3	3	A3
--分析not exists执行过程
select id,name from A where not exists(select * from B where B.AID=1);
--结果如下:为空
select id,name from A where not exists(select * from B where B.AID=2);
--结果如下:为空
select id,name from A where not exists(select * from B where B.AID=3);
--结果如下:
--1	1	A1
--2	2	A2
--3	3	A3
--综上分析,应该是下面这种
select id,name from A where not exists(select * from B where A.ID=1);
--结果如下:
--2	2	A2
--3	3	A3
select id,name from A where not exists(select * from B where A.ID=2);
--结果如下:
--1	1	A1
--3	3	A3
select id,name from A where not exists(select * from B where A.ID=3);
--结果如下:
--1	1	A1
--2	2	A2


4.综上所述,exists和not exists可以实现和in/not in相同的查询效果,不过好像用exists查询时好像是用了索引,查询的效率较高。另外,两种查询都属于多表的关联查询,in用的是子查询,exists使用的是条件查询。in查询时字句一般返回一个字段,exists子句则作为主句查询的条件存在。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: