小弟最近查Oracel数据库时遇到点问题,希望热心网友能指点下我
问题如下!
有表A和表B,两张表都只有字段名:name,没有主键,表A数据10万,表B数据12万。现查询表A中有多少个name和表B的name一样,有多少不一样,SQL如下
--查询name相同个数,记SQL1
select count(*) from(
select distinct name from A
where A.name in (select distinct B.name from B))
--查询name不同个数,记SQL2
select count(*) from(
select distinct name from A
where A.name not in (select distinct B.name from B))
执行以上两条sql,发现SQL1查询总数8万,但是SQL2查询总数是0条记录(SQL2按理说是4万条记录才对呀)
--SQL2改写,记SQL3
select count(*)
(select distinct C.name from A C
where C.name not int
( select distinct name from A
where A.name in (select distinct B.name from B))
执行SQL3,这样查询结果是4万条记录,请问各位,为什么执行SQL2返回的是0条记录呀?
首先,in跟not in是不是相反的。sql2返回0是因为子查询包含空记录,也就是存在b表存在name为空的情况。
而在sql中使用的逻辑是三逻辑,不同于其他语言的两个逻辑,也就是true和false,sql还多了一个unknown.当子查询包含有空的时候,
父字段判断是否等于子查询字段空的时候,都会是false,于是导致为0.
但是,我们可以使用exist和not exist,这两个是相反的,具体为什么,请自行百度。
哎呀,我这个脑子,你也知道name是有重复的,in查出来8W,你咋就能确定not in查出来4W呢?就算name没有重复的,你查的也是A表,也是2W啊。另外你这个sql,效率极低。你验证数据的时候,你先查出来A表有几个name
select count(distinct name) from A;
然后查和B表name一样的
select count(distinct A.name) from A,B where A.name = B.name;
然后查和B表name不一样的
select count(distinct A.name) from A left join B on A.name = B.name where B.name is null;
看看第一个sql查出来的数是不是等于剩下两个sql查出来的数加起来。
select count(*) from A where A.name in(select B.name from B)//相同数
select count(*) from A where A.name not in(select B.name from B)//相同数