1

I have a table A

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

and a table B

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

In my case table B is a subset of table A or table A is a superset of table B (Its a table of items already inventoried). Is there a way to get a list of records of group1 from table A not present in table B? Not sure if there is a set operation to get records from super set not contained in the subset (mutual exclusion)?

Currently I am using the following representational query. Is this the right way of accomplishing this? I am currently working in SQL server, but would appreciate answers pertaining to Oracle and MySQL as well.

SELECT itemid, itemname, itemgroup 
  FROM tableA 
 WHERE itemid NOT IN (SELECT itemid 
                        FROM tableB 
                       WHERE invid = parameter)
One-One
  • 321
  • 1
  • 15
  • 32
  • @OMGPonies edited question. Currently working with SQL server, but would it be possible with Oracle or MySQL. – One-One Mar 10 '12 at 04:08

2 Answers2

3

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

Malk
  • 11,855
  • 4
  • 33
  • 32
  • The LEFT JOIN/IS NULL is only more for performant on MySQL, and when the columns compared are not nullable: 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/) – OMG Ponies Mar 10 '12 at 04:39
2

I think your query is OK but you could also do:

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

You could also do an outer join.

David Faber
  • 12,277
  • 2
  • 29
  • 40