Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
存在的SQL不具有相同的计数_Sql - Fatal编程技术网

存在的SQL不具有相同的计数

存在的SQL不具有相同的计数,sql,Sql,我想找出两张桌子之间的区别 select * from table1 as t1 where exists (select * from table2 as t2 where t1.field1 = t2.field1 and t1.field2 = t2.field2 and t1.field3 = t2.field3) 这将返回939234个匹配项 select * from table2 as

我想找出两张桌子之间的区别

select *
from table1 as t1
where exists (select * from table2 as t2
              where t1.field1 = t2.field1 
                and t1.field2 = t2.field2 
                and t1.field3 = t2.field3)
这将返回939234个匹配项

select *
from table2 as t2
where exists (select * from table1 as t1
              where t2.field1 = t1.field1 
                and t2.field2 = t1.field2 
                and t2.field3 = t1.field3)
这将返回938796个匹配项

我不应该期望两个数字都是一样的吗


要找到两个表中的差异,我只需将
where exists
更改为
where not exists
对吗?

否,您不应该期望两个查询返回相同数量的行。让我们考虑一个更简单的例子:

表1:

id     val
 1      1
 2      1
表2:

val
 1
此查询返回
1
,因为
表2中有一行匹配:

select count(*)
from table2 t2
where exists (select 1 from table1 t1 where t1.val = t2.val);
此查询返回
2
,因为两行匹配:

select count(*)
from table1 t1
where exists (select 1 from table2 t2 where t1.val = t2.val);

换句话说,这些表可能有重复项。当该表位于
from
子句中时,重复项将作为单独的行返回。当该表位于相关子查询中时,不计算重复项。

否,您不应该期望两个查询返回相同数量的行。让我们考虑一个更简单的例子:

表1:

id     val
 1      1
 2      1
表2:

val
 1
此查询返回
1
,因为
表2中有一行匹配:

select count(*)
from table2 t2
where exists (select 1 from table1 t1 where t1.val = t2.val);
此查询返回
2
,因为两行匹配:

select count(*)
from table1 t1
where exists (select 1 from table2 t2 where t1.val = t2.val);

换句话说,这些表可能有重复项。当该表位于
from
子句中时,重复项将作为单独的行返回。当该表位于相关子查询中时,不计算重复项。

我删除了不兼容的数据库标记。请仅使用您真正使用的数据库进行标记。不确定为什么不获得相同数量的行。但是,为什么不尝试
select t1.*从t1.field1=t1.field1上的表t1内部连接表2 t2…
I删除了不兼容的数据库标记。请仅使用您真正使用的数据库进行标记。不确定为什么不获得相同数量的行。但是,为什么不尝试
选择t1.*从t1.field1=t1.field1上的tablel t1内部联接table2 t2…
我没有考虑重复项。。。我错误地假设了唯一性。@Tarik。我花了一点时间才理解你的困惑。然后我意识到你在想“嘿,这些是获得表之间重叠的等效方法。为什么结果不同?”起初,我真的没有想到为什么有人会认为这些是相同的。然而,经过一番思考,我明白了为什么这会令人困惑。作为将来的参考,重复和
NULL
值通常是导致非直观行为的原因。我没有考虑重复。。。我错误地假设了唯一性。@Tarik。我花了一点时间才理解你的困惑。然后我意识到你在想“嘿,这些是获得表之间重叠的等效方法。为什么结果不同?”起初,我真的没有想到为什么有人会认为这些是相同的。然而,经过一番思考,我明白了为什么这会令人困惑。为了便于将来参考,重复和
NULL
值通常是导致非直观行为的原因。