如何理解 select * from B where (select count(1) as num from A where A.ID = B.ID) = 0
为什么 可以在B表中 排除A表的数据
假设个例子吧:A表
id 姓名 性别
00 aa 女
01 bb 女
02 cc 女
B表
id 姓名 性别
00 aa 女
02 cc 女
03 dd 男
select * from B是执行B表;
count(1) 表示统计表中符合where条件的所有的记录数,不会忽略NULL,包含字段为null 的记录;
as num就是定义了字段名是num,并且将得到结果放到字段NUM中;
select * from B where ?= 0 where中条件其实是,什么等于0?
代入 (select count(1) as num from A where A.ID = B.ID) 就是A和B通过ID连接后,COUNT(*)计数=0;
当执行id=‘00’时 ,A表和B表中有相同的值,因此select count(1) as num from A where A.ID = B.ID 的执行结果 自定义字段num不等于0, 所以运行结果没有第一行id=‘00’,
当执行id=‘02’时,A表和B表中有相同的值,因此select count(1) as num from A where A.ID = B.ID 的执行结果 自定义字段num不等于0, 所以运行结果没有第二行id=‘02’,
执行id= ‘03’时,A表和B表中没有相同的值,因此select count(1) as num from A where A.ID = B.ID 的执行结果,自定义字段num等于0 ,符合条件,所以运行结果会有第三行。
运行结果为:
id 姓名 性别
03 dd 男
所以:可以在B表中 排除A表的数据。
select * from B where (select count(1) as num from A where A.ID = B.ID) = 0
整个语句的意思就是统计B表和A表用ID连接的行数,子查询的行数num=0,就可以实现从B表中排除A表数据。