2011-10-29 46 views
0

我需要比較不同數據庫中相似表之間的行值。我怎麼知道哪些行是不同的。如何在表格中的行之間做差異

例如db1.foo (contains 2000 rows) and db2.foo (contains 2003 rows)。這兩個表應該是相似的,我想知道如何找到應該添加的行。注意:即使這些表中的主鍵ID也應該是相同的。

我無法訪問任何GUI工具,並想知道是否有任何SQL命令可用於執行此差異?

回答

0

僅依靠主鍵檢查:

SELECT 
     'a' AS DataOnlyInTable 
     , a.* 
    FROM 
     db1.foo AS a 
     LEFT JOIN 
     db2.foo AS b 
      ON b.PK = a.PK 
    WHERE b.PK IS NULL 
UNION ALL 
    SELECT 
     'b' AS DataOnlyInTable 
     , b.* 
    FROM 
     db1.foo AS a 
     RIGHT JOIN 
     db2.foo AS b 
      ON b.PK = a.PK 
    WHERE a.PK IS NULL 

根據全行檢查:

SELECT 
     'a' AS DataOnlyInTable 
     , a.* 
    FROM 
     db1.foo AS a 
     LEFT JOIN 
     db2.foo AS b 
      ON (b.PK, b.column2, b.column3, ...) 
      = (a.PK, a.column2, a.column3, ...) 
    WHERE b.PK IS NULL 
UNION ALL 
    SELECT 
     'b' AS DataOnlyInTable 
     , b.* 
    FROM 
     db1.foo AS a 
     RIGHT JOIN 
     db2.foo AS b 
      ON (b.PK, b.column2, b.column3, ...) 
      = (a.PK, a.column2, a.column3, ...) 
    WHERE a.PK IS NULL