如何比较两个表?
How to compare between two tables?
这是我的查询
select * from table as a
where a.* not in
(select * from table B)
我想知道两个表之间的区别有一个特定的功能吗?
根据定义,EXCEPT returns 不同的行通过比较两个查询的结果。
EXCEPT returns 来自左侧输入查询但右侧输入查询未输出的不同行。
基本规则是:
- 所有列的数量和顺序必须相同
查询。
- 数据类型必须兼容。
CREATE TABLE MyTableA (ColA int, ColB int)
CREATE TABLE MyTableB (ColA int, ColB int)
INSERT INTO MyTableA (ColA, ColB) VALUES (15,1),(10,1),(2,1),(2,1),(16,1),(2,2),(3,3),(3,3)
INSERT INTO MyTableB (ColA, ColB) VALUES (1,1),(1,1),(1,1),(2,2),(4,5),(1,1),(4,5)
GO
SELECT * FROM MyTableA
EXCEPT
SELECT * FROM MyTableB
Select *
from MyTableA as a where not exists (Select 1 from MyTableB as b
where a.ColA = b.ColA and a.ColB = b.ColB)
GO
ColA | ColB
---: | ---:
2 | 1
3 | 3
10 | 1
15 | 1
16 | 1
ColA | ColB
---: | ---:
15 | 1
10 | 1
2 | 1
2 | 1
16 | 1
3 | 3
3 | 3
db<>fiddle here
您可以看到使用 EXCEPT 生成了重复的条目,如果您想摆脱它,您可能需要两个表的 ID 列并将查询更新为:
Select *
from MyTableA as a where not exists (Select 1 from MyTableB as b
where a.ColA = b.ColA and a.ColB = b.ColB and a.ID <> b.ID)
这是我的查询
select * from table as a
where a.* not in
(select * from table B)
我想知道两个表之间的区别有一个特定的功能吗?
根据定义,EXCEPT returns 不同的行通过比较两个查询的结果。
EXCEPT returns 来自左侧输入查询但右侧输入查询未输出的不同行。
基本规则是:
- 所有列的数量和顺序必须相同 查询。
- 数据类型必须兼容。
CREATE TABLE MyTableA (ColA int, ColB int) CREATE TABLE MyTableB (ColA int, ColB int) INSERT INTO MyTableA (ColA, ColB) VALUES (15,1),(10,1),(2,1),(2,1),(16,1),(2,2),(3,3),(3,3) INSERT INTO MyTableB (ColA, ColB) VALUES (1,1),(1,1),(1,1),(2,2),(4,5),(1,1),(4,5)
GO
SELECT * FROM MyTableA EXCEPT SELECT * FROM MyTableB Select * from MyTableA as a where not exists (Select 1 from MyTableB as b where a.ColA = b.ColA and a.ColB = b.ColB) GO
ColA | ColB ---: | ---: 2 | 1 3 | 3 10 | 1 15 | 1 16 | 1 ColA | ColB ---: | ---: 15 | 1 10 | 1 2 | 1 2 | 1 16 | 1 3 | 3 3 | 3
db<>fiddle here
您可以看到使用 EXCEPT 生成了重复的条目,如果您想摆脱它,您可能需要两个表的 ID 列并将查询更新为:
Select *
from MyTableA as a where not exists (Select 1 from MyTableB as b
where a.ColA = b.ColA and a.ColB = b.ColB and a.ID <> b.ID)