2009-12-29 31 views
0

我有兩個表A & B我想有一個查詢: 返回TRUE只有當兩個表是相同的(我的意思是A中的每一行都存在B &反之,無論是線序)PostgreSQL查詢兩個表之間的相等性

我使用關鍵字EXCEPT,但在許多情況下不工作

感謝您的幫助。

+0

請發表你試了一下,以及表A和表B中的列表。 – 2009-12-29 10:15:30

+0

您的數據集有多大?除了遇到什麼問題? – 2009-12-29 10:16:57

+0

數據集非常小(少於20行)並且查詢僅用於調試而不用於生產。 – adam 2009-12-29 10:34:06

回答

6
select * from tablea except all select * from tableb 

返回tablea中不存在的所有行。

做它周圍的其他方法

select * from tableb except all select * from tablea 

收益表B中的所有行不TableA中存在。

所以,現在我們可以:

select count(*) from (select * from tablea except all select * from tableb) x; 

得到的TableA中 「壞」 的行數和:

select count(*) from (select * from tableb except all select * from tablea) x; 

得到的表B中的 「壞」 的行數。

表是相同的,如果這兩點都爲0,並因爲無論計數可大於零少,那麼我們可以測試數的總和爲0:

select 0 = (select count(*) from (select * from tablea except all select * from tableb) x) + (select count(*) from (select * from tableb except all select * from tablea) x); 
+0

謝謝你!除了+運營商的位置,它工作正常。 – adam 2009-12-29 13:34:56

+1

如果它解決了你的問題,你應該接受答案 – 2011-01-30 23:11:27