2012-03-10 19 views
1

我有一個table A獲取不包含在一個子集(互斥)的超集記錄

itemid  itemname  itemgroup 
    1  item1  group1 
    2  item2  group1 
    3  item3  group1 

table B

itemid  itemname  itemgroup  invid 
    1  item1  group1   1 
    3  item3  group1   1 

在我的情況table Btable Atable A一個子集是超文本的table B(其中一個項目表已經清單)。有沒有辦法從table A獲得group1的記錄列表,但不存在於table B?不確定是否有一組操作從超集中獲取不包含在子集中的記錄(互斥)?

目前我正在使用以下代表性查詢。這是完成這個的正確方法嗎?我目前在SQL服務器上工作,但也會很感謝與Oracle和MySQL有關的答案。

SELECT itemid, itemname, itemgroup 
    FROM tableA 
WHERE itemid NOT IN (SELECT itemid 
         FROM tableB 
         WHERE invid = parameter) 
+1

爲了什麼數據庫? – 2012-03-10 04:03:24

+0

@OMGPonies編輯的問題。目前使用SQL服務器,但是使用Oracle或MySQL可能。 – 2012-03-10 04:08:56

回答

2

我覺得你的查詢是確定的,但你也可以這樣做:

SELECT * FROM tableA a 
WHERE NOT EXISTS (SELECT b.itemid FROM tableB b WHERE b.itemid = a.itemid 
         AND b.invid = parameter) 

你也可以做外連接。

2

http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins

SELECT  * 
FROM  TableA A 
LEFT JOIN TableB B ON A.itemid = B.itemid AND B.invid = parameter 
WHERE  B.itemid IS NULL 

http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins

+0

LEFT JOIN/IS NULL僅用於MySQL的性能,當比較的列不可爲空時:http://explainextended.com/2009/09/18/not-in-vs-not-exists-vs- left-join-is-null-mysql/[SQL Server](http://explainextended.com/2009/09/15/not-in-vs-not-exists-vs-left-join-is-null-sql -server /),[Oracle](http://explainextended.com/2009/09/17/not-in-vs-not-exists-vs-left-join-is-null-oracle/) – 2012-03-10 04:39:59