0

我找到了 Jeff Smith 的解决方案,它显示了两个表之间的差异:

SELECT MIN(TableName) as TableName, ID, COL1, COL2, COL3 ...
FROM
(
  SELECT 'Table A' as TableName, A.ID, A.COL1, A.COL2, A.COL3, ...
  FROM A
  UNION ALL
  SELECT 'Table B' as TableName, B.ID, B.COL1, B.COl2, B.COL3, ...
  FROM B
) tmp
GROUP BY ID, COL1, COL2, COL3 ...
HAVING COUNT(*) = 1
ORDER BY ID

在我的项目中,我需要比较例如。仅 col1 和 col2,rest 用于其他操作。我试着用

HAVING (COUNT(col1) = 1 and COUNT(col2) = 1) 

但没有效果。

您能否为我提供解决方案?

4

2 回答 2

3
  1. 获取使用 EXCEPT中不存在的COL1COL2in的值:AB

    SELECT COL1, COL2 FROM A
    EXCEPT
    SELECT COL1, COL2 FROM B
    
  2. 将结果用作派生表将它们连接回A并获取所有列:

    SELECT 'A' AS SRC, A.COL1, A.COL2, A.COL3...
    FROM (
      SELECT COL1, COL2 FROM A
      EXCEPT
      SELECT COL1, COL2 FROM B
    ) AS diff
    INNER JOIN A ON diff.COL1 = A.COL1 AND diff.COL2 = A.COL2
    
  3. 类似地,使用 EXCEPT 获取仅存在于 中的COL1和的值,并加入结果集以获取相应的完整行。COL2BB

  4. 将这两组与 UNION ALL 结合起来:

    SELECT 'A' AS SRC, A.COL1, A.COL2, A.COL3...
    FROM (
      SELECT COL1, COL2 FROM A
      EXCEPT
      SELECT COL1, COL2 FROM B
    ) AS diff
    INNER JOIN A ON diff.COL1 = A.COL1 AND diff.COL2 = A.COL2
    
    UNION ALL
    
    SELECT 'B' AS SRC, B.COL1, B.COL2, B.COL3...
    FROM (
      SELECT COL1, COL2 FROM B
      EXCEPT
      SELECT COL1, COL2 FROM A
    ) AS diff
    INNER JOIN B ON diff.COL1 = B.COL1 AND diff.COL2 = B.COL2
    ;
    
于 2013-10-17T02:44:44.397 回答
0

您正在从错误的位置删除列。您应该将其从列列表中删除,而不是从星号中删除:

SELECT MIN(TableName) as TableName, ID, COL1, COL2
FROM
(
  SELECT 'Table A' as TableName, A.ID, A.COL1, A.COL2
  FROM A
  UNION ALL
  SELECT 'Table B' as TableName, B.ID, B.COL1, B.COl2
  FROM B
) tmp
GROUP BY ID, COL1, COL2
HAVING COUNT(*) = 1
ORDER BY ID

要保留结果中的其他列,您可以使用MIN(或朋友)保留它们:

SELECT MIN(TableName) as TableName, ID, COL1, COL2, MIN(COL3), MIN(COL4), ...
FROM
(
  SELECT 'Table A' as TableName, A.ID, A.COL1, A.COL2, A.COL3, A.COL4, ...
  FROM A
  UNION ALL
  SELECT 'Table B' as TableName, B.ID, B.COL1, B.COL2, B.COL3, B.COL4, ...
  FROM B
) tmp
GROUP BY ID, COL1, COL2
HAVING COUNT(*) = 1
ORDER BY ID

请注意,这在某些情况下效果不佳。如果两个表中的两行相同(包括 ID),那么即使不是,它也会发现它是不同的。此外,在这个版本中,如果您有多个相同的行COL1COL2那么这也不能很好地工作。我会将这两个表连接在一起以进行更可靠的比较。

于 2013-10-15T17:34:18.570 回答