【mysql】3.exists和not exists练习

 exists和not exists返回的结果:true、false;查询过程中数据是和子查询相关联的数据作为判断。

exists和not exists作为where条件,跟随主表返回的是主表的数据。

exists:表示存在于。

not 恶习水头损失:表示不包含,与existss相反。

#建表
create  table tablea
(aid varchar(20),
aname varchar(20),
asex varchar(20));

create table tableb
(bid varchar(20),
bname varchar(20),
bsex varchar(20),
baddress varchar(20));

#插入数据 dual表示虚拟表 aa bb cc 是虚拟表的自定义字段
insert into tablea
select 1 aa,'张晋娟' bb,'女' cc from dual union all
select 2 aa,'张翠兰' bb,'女' cc from dual union all
select 3 aa,'李海滨' bb,'男' cc from dual union all
select 4 aa,'马艳艳' bb,'女' cc from dual union all
select 5 aa,'邓事文' bb,'男' cc from dual;

insert into tableb
select '1' aaa,'马艳艳' bb,'女' cc,'太原' dd from dual union all
select '2' aaa,'谭建军' bb,'男' cc,'长沙' dd from dual union all
select '3' aa,'李红军' bb,'男' cc,'长沙' dd from dual union all
select '4' aaa,'丁秀娟' bb,'女' cc,'北京' dd from dual union all
select '5' aaa,'邓事文' bb,'男' cc,'深圳' dd from dual ;
-- 练习exists和notexists
-- a表和b表都有的信息
-- a表和b表只有张晋娟的信息
-- 两表无关联,where返回true,只是查询a表的信息
-- b中没有a表有的人物信息
-- 两表无关联,where返回false,不返回任何数据
-- b中不存在具有‘张晋娟’的信息



-- a表和b表都有的信息
select * from tablea a where exists(select * from tableb  where a.aname=bname);

-- a表和b表只有张晋娟的信息
select * from tablea a where exists(select * from tableb b where a.aID=1);

-- 两表无关联,where返回true,只是查询a表的信息
select * from tablea a where exists(select bid from tableb );

-- b中没有a表有的人物信息
select * from tablea a where not exists(select * from tableb b where a.aname=b.bname);

-- 两表无关联,where返回false,不返回任何数据
select * from tablea a where not exists(select * from tableb b where b.bID=4);

-- b中不存在具有‘张晋娟’的信息
select * from tablea a where not exists(select * from tableb b where a.aID=1);

  • 13
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值