1.
# exists 和 not exists 的区别:
# ① exists : exists 后面括号里返回的是 "true" ,则 当前记录满足条件 (包含:查总数发现 count 是 1 ,true 满足要求)
# not exists : not exists 返回的是 "false" ,则 当前记录满足条件(不包含:查总数发现 count 是 0 满足要求)
# ② 用法:
# exists (select 1 from B)
# not exists (select 1 from B)
# 错误用法:
# exists (select count(1) from B)
# not exists (select count(1) from B)
# 说明: select 1 这里的 1 其实是 无关紧要的,换成 * , 0 也没问题,他只在乎括号里的数据能不能查得出来,是否存在这样的记录,如果存在 ,当前数据就满足条件
# 能查出来的情况:
# +-+
# |1|
# +-+
# |1|
# +-+
# 不能查出来的情况
# # +-+
# # |1|
# # +-+
select * from boy ;
# +--+----+
# |id|name|
# +--+----+
# |1 |慕容皝 |
# |2 |慕容垂 |
# |3 |慕容博 |
# |4 |慕容复 |
# +--+----+
select * from girl ;
# +--+----+------+
# |id|name|boy_id|
# +--+----+------+
# |1 |A |1 |
# |2 |B |2 |
# |3 |C |3 |
# +--+----+------+
# 有女朋友的 boy (exists )
select * from boy where exists(select 1 from girl where boy.id = girl.boy_id);
# +--+----+
# |id|name|
# +--+----+
# |1 |慕容皝 |
# |2 |慕容垂 |
# |3 |慕容博 |
# +--+----+
# 将 1 换成 *
select * from boy where exists(select * from girl where boy.id = girl.boy_id);
# +--+----+
# |id|name|
# +--+----+
# |1 |慕容皝 |
# |2 |慕容垂 |
# |3 |慕容博 |
# +--+----+
# 错误写法: 原因:boy 为 4 : select count(1) from girl where girl.boy_id = 4 查到的结果 是 0 , 0 也是 值
select count(1) from girl where girl.boy_id = 4 ;
# +--------+
# |count(1)|
# +--------+
# |0 |
# +--------+
# 没值的情况
select 1 as A from girl where girl.boy_id = 4 ;
# +-+
# |1|
# +-+
# 没值的情况
select * from girl where girl.boy_id = 4 ;
# +-+
# |1|
# +-+
# 有值的情况(满足条件的情况)
select 1 from girl where girl.boy_id = 3 ;
# +-+
# |1|
# +-+
# |1|
# +-+
select 0 from girl where girl.boy_id = 3 ;
# +-+
# |0|
# +-+
# |0|
# +-+
select * from girl where girl.boy_id = 3 ;
# +--+----+------+
# |id|name|boy_id|
# +--+----+------+
# |3 |C |3 |
# +--+----+------+
select * from boy where exists(select count(1) from girl where boy.id = girl.boy_id);
# +--+----+
# |id|name|
# +--+----+
# |1 |慕容皝 |
# |2 |慕容垂 |
# |3 |慕容博 |
# |4 |慕容复 |
# +--+----+
#
select * from boy where exists(select count(*) from girl where boy.id = girl.boy_id);
# +--+----+
# |id|name|
# +--+----+
# |1 |慕容皝 |
# |2 |慕容垂 |
# |3 |慕容博 |
# |4 |慕容复 |
# +--+----+
# 不推荐写法:
select * from boy where exists(select count(1) from girl where boy.id = girl.boy_id group by girl.boy_id having count(1) >=1 );
# +--+----+
# |id|name|
# +--+----+
# |1 |慕容皝 |
# |2 |慕容垂 |
# |3 |慕容博 |
# +--+----+
# not exists 的用法: 单身男生
select * from boy where not exists(select 1 from girl where boy.id = girl.boy_id );
# +--+----+
# |id|name|
# +--+----+
# |4 |慕容复 |
# +--+----+
# not exists 不存在 () ,括号里 查出来没有,就代表不存在
select 1 from girl where girl.boy_id = 4 ;
# 没有
# +-+
# |1|
# +-+
select 1 from girl where girl.boy_id in(1,2,3) ;
# +-+
# |1|
# +-+
# |1|
# |1|
# |1|
# +-+