2010-10-31 172 views
2

我有兩個SQLite表我想比較。要設置表:比較兩個SQLite表的差異

CREATE TABLE A (Value); 
CREATE TABLE B (Value); 

INSERT INTO A VALUES (1); 
INSERT INTO A VALUES (1); 

INSERT INTO B VALUES (2); 
INSERT INTO B VALUES (1); 

我比較兩張表得到的最接近是使用下面的SQL:

SELECT 'A' AS Diff, * 
FROM (SELECT * FROM A EXCEPT SELECT * FROM B) 
UNION ALL 
SELECT 'B' AS Diff, * 
FROM (SELECT * FROM B EXCEPT SELECT * FROM A) 

我想要的結果是

A; 1 
B; 2 

不過,我只得到

B; 2 

因爲t他除了關鍵字刪除所有來自表A的1,無論表B中有多少個1。

我應該如何比較這兩個表?

+0

你的表的設計是有點太簡單了。介紹另一列,實際上會導致值爲1的行不同,否則您將無法獲得結果。 – 2010-10-31 04:52:35

回答

1

你可以嘗試使用 -

select Distinct A.Value as Avalue,B.Value as Bvalue from a inner join B on A.Value <> B.Value 

這應該給你一個結果 -

AValue | BValue 
    1  |  2 

我用了一個獨特的,因爲主鍵或唯一身份定義你的表沒有等有沒有Distinct的這個查詢可能會顯示重複。

你也可以嘗試使用一些免費的數據庫比較工具,可用於複雜的比較。有些工具可以比較表格,程序等。這些工具也會爲差異生成腳本。但是,我從來沒有隻爲sql lite提供這樣的工具。所以,我不確定這些工具是否適用於sql lite。

0

我找到了答案。如果表有多個列,那麼代碼很多,但我可以使用相同的模式以編程方式生成SQL。

/* Create Example Data */  
CREATE TABLE A (TheValue);  
CREATE TABLE B (TheValue);  
INSERT INTO A VALUES (1);  
INSERT INTO A VALUES (1);  
INSERT INTO B VALUES (2);  
INSERT INTO B VALUES (1);  

/* Format data */  
CREATE TABLE TmpA (Id INTEGER PRIMARY KEY, TheValue);  
CREATE TABLE TmpB (Id INTEGER PRIMARY KEY, TheValue);  
INSERT INTO TmpA (TheValue) SELECT * FROM A ORDER BY TheValue;  
INSERT INTO TmpB (TheValue) SELECT * FROM B ORDER BY TheValue;  
CREATE INDEX idx_TmpA ON TmpA (TheValue ASC);  
CREATE INDEX idx_TmpB ON TmpB (TheValue ASC);  

/* Result */   
SELECT 'A' AS Diff, *  
FROM   
(  
     SELECT Id - (SELECT Min(Id) FROM TmpA AS A2 WHERE A2.TheValue = TmpA.TheValue) AS SubNum, TheValue 
     FROM TmpA 
     EXCEPT 
     SELECT Id - (SELECT Min(Id) FROM TmpB AS A2 WHERE A2.TheValue = TmpB.TheValue) AS SubNum, TheValue 
     FROM TmpB 
)  
UNION ALL  
SELECT 'B' AS Diff, *  
FROM   
(  
     SELECT Id - (SELECT Min(Id) FROM TmpB AS A2 WHERE A2.TheValue = TmpB.TheValue) AS SubNum, TheValue 
     FROM TmpB 
     EXCEPT 
     SELECT Id - (SELECT Min(Id) FROM TmpA AS A2 WHERE A2.TheValue = TmpA.TheValue) AS SubNum, TheValue 
     FROM TmpA 
)  
1

你也可以簡單地使用像DiffKit工具:

www.diffkit.org