在更深层次的视图中编写视图和嵌套视图时,我有时会遗漏某些内容并最终丢失行/数据。如何检查两个不同表中的列是否与数据完全匹配?
示例:
select count(distinct table1.col1)
from table1
where table1.col1 not in (select distinct table2.col1
from table2);
这将返回table1.col1中不在table2中的值的数量。但是,我不知道这是一个很好的解决方案,因为它不计算table1.col1中不存在的table2.col1值。
答案 0 :(得分:6)
您可以使用两个EXCEPT
个查询(或联合它们)来检查:
SELECT DISTINCT col1
FROM table1
EXCEPT
SELECT DISTINCT col1
FROM table2
这将显示table1中存在的值,但不显示table2中存在的值。然后再次运行,表格名称翻转为相反。
答案 1 :(得分:3)
使用:
SELECT MAX(x.t1_missing_count) AS t1_missing_count,
MAX(x.t2_missing_count) AS t2_missing_count
FROM (
SELECT COUNT(DISTINCT t1.col1) AS t1_missing_count,
NULL AS t2_missing_count
FROM TABLE_1 t1
WHERE t1.col1 NOT IN (SELECT DISTINCT t2.col1
FROM TABLE_2 t2)
UNION ALL
SELECT NULL,
COUNT(DISTINCT t2.col1),
FROM TABLE_2 t2
WHERE t2.col1 NOT IN (SELECT DISTINCT t1.col1
FROM TABLE_1 t1)) x
答案 2 :(得分:1)
select count(*) from (
select
table1.col1 from table1 left join table2 on table1.col1 = table2.col2
where table2.col1 is null
union
select table2.col1 from table2 left join table 1 on table2.col1 = table1.col1
where table1.col1 is null
)
答案 3 :(得分:0)
declare @count int, @count2 int
select @count = count(distinct table1.col1)
from table1
where table1.col1 not in (select distinct table2.col1
from table2)
select @count2 = count(distinct table2.col1)
from table2
where table2.col1 not in (select distinct table1.col1
from table1)
select @count + @count2