查询比较两个表是否相同表示表不相同时表是相同的

时间:2015-09-11 08:47:57

标签: sql sql-server sql-server-2008 sql-server-2012

tableA包含列a,b,c,d,e,f,g

tableB有列a,b,c,d,e,f,g,i,j,k,l,m,n,o

我想看看tableA中列a到g的数据是否与tableB列a到g中的数据相同。我正在使用此查询

select a,b,c,d,e,f,g from tableA
union
select a,b,c,d,e,f,g from tableB
except 
select a,b,c,d,e,f,g from tableA
intersect 
select a,b,c,d,e,f,g from tableB

我应该提到'a'的名称与abc_1c, abc_5c, cfg_10x类似,依此类推,'b'date

如果这些列上的表格相同,则他们不应该返回任何内容。唯一的问题是tableA有180576行,tableB有181404行。在哪里我犯了错误,我怎么能得到我想要的东西?

由于

1 个答案:

答案 0 :(得分:1)

这将获得像XOR

这样的表之间不同的数据

<强> SqlFiddle

(select a,b,c,d,e,f,g, 'tableA' AS [source] from tableA
except
select a,b,c,d,e,f,g, 'tableA' from tableB)
union all
(select a,b,c,d,e,f,g, 'tableB' AS [source] from tableB
except
select a,b,c,d,e,f,g, 'tableB' from tableA);

或:

(select a,b,c,d,e,f,g from tableA
UNION ALL
select a,b,c,d,e,f,g from tableB)
EXCEPT
(select a,b,c,d,e,f,g from tableB
INTERSECT
select a,b,c,d,e,f,g from tableA);

因此,如果没有返回的行,则表格是相同的。

修改

您可能在其中一个表格中有重复项,请尝试:

SELECT a,b,c,d,e,f,g, COUNT(*)
FROM tableB    /* or tableA */
GROUP BY a,b,c,d,e,f,g
HAVING COUNT(*) > 1

将检测重复的增强版本:

<强> SQLFIDDLE

(SELECT
   a,b,c,d,e,f,g,
   [source] = 'tableA',
   [rn] = ROW_NUMBER() OVER(PARTITION BY a,b,c,d,e,f,g ORDER BY (SELECT 1))
FROM tableA
EXCEPT
SELECT
   a,b,c,d,e,f,g,
   [source] = 'tableA',
   [rn] = ROW_NUMBER() OVER(PARTITION BY a,b,c,d,e,f,g ORDER BY (SELECT 1))
FROM tableB)
UNION ALL
(SELECT
   a,b,c,d,e,f,g,
   [source] = 'tableB',
   [rn] = ROW_NUMBER() OVER(PARTITION BY a,b,c,d,e,f,g ORDER BY (SELECT 1))
FROM tableB
EXCEPT
SELECT
   a,b,c,d,e,f,g,
   [source] = 'tableB',
   [rn] = ROW_NUMBER() OVER(PARTITION BY a,b,c,d,e,f,g ORDER BY (SELECT 1))
FROM tableA)