WHERE EXISTS和INTERSECT之间的T-SQL区别

时间:2018-01-28 05:21:41

标签: sql-server tsql

你能告诉我这两者有什么区别吗? 我曾尝试使用它们比较两个表,但结果有点不同:

  SELECT a.CustID FROM tbl1 AS a 
  WHERE EXISTS (SELECT b.CustID FROM tbl2 b WHERE (a.CustID=b.CustID))

此查询结果为178行。但是,下面的查询会产生162行。

  SELECT a.CustID FROM tbl1 AS a
  INTERSECT
  SELECT b.CustID FROM tbl2 AS b

1 个答案:

答案 0 :(得分:3)

如果您在 tbl1

中有重复的 CustId ,则以下查询会产生多行
  SELECT a.CustID FROM tbl1 AS a 
  WHERE EXISTS (SELECT b.CustID FROM tbl2 b WHERE (a.CustID=b.CustID))

如果您使用INTERSECT,将删除重复

  SELECT a.CustID FROM tbl1 AS a
  INTERSECT
  SELECT b.CustID FROM tbl2 AS b

例如。

CREATE TABLE tbl1 (CustId int, CustName varchar(100))
GO
INSERT INTO tbl1 VALUES(1 ,'N1')
GO
INSERT INTO tbl1 VALUES(2 ,'N2')
GO
INSERT INTO tbl1 VALUES(1 ,'N3')
GO
CREATE TABLE tbl2 (CustId int, CustName varchar(100))
GO
INSERT INTO tbl2 VALUES (1 ,'N1')
GO

对于上表,如果你运行

 SELECT a.CustID FROM tbl1 AS a 
  WHERE EXISTS (SELECT b.CustID FROM tbl2 b WHERE (a.CustID=b.CustID))

您将获得2条记录。

如果你跑

   SELECT a.CustID FROM tbl1 AS a
  INTERSECT
  SELECT b.CustID FROM tbl2 AS b

你将获得1条记录。

注意:如果对查询1使用 DISTINCT ,则两者都会产生相同的输出。

  SELECT DISTINCT a.CustID FROM tbl1 AS a 
  WHERE EXISTS (SELECT b.CustID FROM tbl2 b WHERE (a.CustID=b.CustID))