可能最透徹的查詢是這樣的:
SELECT table1.id,
table1.digit,
table1.letter
FROM (SELECT id,
digit,
letter,
ROW_NUMBER() OVER (PARTITION BY digit, letter ORDER BY id) rn
FROM table1
) table1
LEFT
JOIN (SELECT id,
digit,
letter,
ROW_NUMBER() OVER (PARTITION BY digit, letter ORDER BY id) rn
FROM table2
) table2
ON table2.digit = table1.digit
AND table2.letter = table1.letter
AND table2.rn = table1.rn
WHERE table2.id IS NULL
ORDER
BY table1.id
;
,其給出了table1
和table2
「行數」的組「雙胞胎」中的每個記錄。例如,這樣的:
SELECT id,
digit,
letter,
ROW_NUMBER() OVER (PARTITION BY digit, letter ORDER BY id) rn
FROM table1
ORDER
BY table1.id
;
返回此:
ID DIGIT LETT RN
---------- ---------- ---- ----------
1 4 S 1
2 2 P 1
3 5 B 1
4 4 S 2 -- second row with 4 S
5 1 A 1
6 2 P 2 -- second row with 2 P
這就是說,如果你知道,沒有(digit, letter)
都不能出現比table2
一次,可以大大地使用EXISTS
,而不是簡化該ROW_NUMBER()
:
SELECT id,
digit,
letter
FROM table1 table1a
WHERE EXISTS
(SELECT 1
FROM table1
WHERE digit = table1a.digit
AND letter = table1a.letter
AND id < table1a.id
)
OR NOT EXISTS
(SELECT 1
FROM table2
WHERE digit = table1a.digit
AND letter = table1a.letter
)
;
嗨,我可以澄清問題嗎? 您僅在數字和字母上匹配(即,您在Id上不匹配)。 並且表2中的每個條目僅從Table1中排除一個條目(因此對於4 S,Table1中id = 1的行被表2中的id = 3的行排除,但Table1中的id = 4不是? – GregHNZ 2012-03-24 02:40:26
是的,I只看到取消雙胞胎,就像Table1中的id = 1的行被Table2中的id = 3的行取消一樣(Table1中的rowid = 5也被Table2中的rowid = 4取消),但id = 4表1(相同的數字和字母4 S)必須在結果中返回,原因未被Table2中的任何行取消... – slyder07 2012-03-24 03:07:05
因此,如果table2中的id是高於表1中的那個? – 2012-03-25 08:00:06