2012-02-16 30 views
1
的SQL比較

我試圖像成才:,其中表1的值不是在表2中,並顯示結果如表3

Select Items 
From Table1 
Where Not Exists (
    Select Items 
    From Table2 
    Where Table2.Items = Table1.Items) As Table3.Items 

,但不知何故沒有工作,所以可以anywone告訴我怎樣才能實現這一目標?

+0

你給「Table3」賦予結果是什麼意思?結果應該插入table3中嗎? – 2012-02-16 13:54:50

+0

你的意思是說SQL沒有給出預期的結果,或者代碼給你一個錯誤或者運行時沒有給出預期的結果。你能在這裏粘貼相關的代碼嗎? – ImranIlahi 2012-02-16 14:03:36

+0

表3實際上並不是之前創建的另一個表。 它只是將查詢的結果顯示爲表3。 – 2012-02-16 14:31:33

回答

2

如果你想使用這一個新表,你可以試試這個:

Select Items 
Into Table3 
From Table1 
Where Not Exists (Select Items From Table2 Where Table2.Items = Table1.Items) 
+0

不錯,但它創造臨時或永久表? – 2012-02-16 14:45:42

+0

@BerkerYüceer - 這是創建一個新的永久表。如果您只想在另一個查詢中使用它,但不想將其作爲表創建,則可以將其用作派生表:「SELECT .. FROM(從表1中選擇Itmes從表1不存在..... )AS Table3 – Lamak 2012-02-16 14:49:51

+0

是啊我試過那裏,但似乎我誤以爲SELECT * FROM(....)AS TABLE3的用法。它現在的工作謝謝.. – 2012-02-16 14:52:26

1

如果您正在尋找t3行那些在t1存在,但不是在t2,嘗試:

select t3.Items 
from table3 t3 
where exists 
     (
     select * 
     from table1 t1 
     where t1.Items = t3.items 
     ) 
     and not exists 
     (
     select * 
     from table2 t2 
     where t2.Items = t3.items 
     ) 
+0

我想你誤會了我。我只使用Table3來顯示Table1和Table2之間的比較結果,但這是另一個有用的答案,對我來說很有用,所以+1。 – 2012-02-16 14:48:42

1

另一種解決方案是except

select * 
from 
(
    Select Items 
    From Table1 
    except 
    Select Items 
    From Table2 
) as Table3 
+0

不錯,我喜歡這個 – 2012-02-16 14:32:12

相關問題