views:

68

answers:

1

I have two tables:

Table A

  • ID
  • ABC_ID
  • VAL

Table B

  • ID
  • ABC_ID
  • VAL

These two tables are directly related to each other through the ABC_ID column.

I want to find all the VAL column values in table A which are not present in table B for the same ABC_ID.

+2  A: 
SELECT A.ABC_ID, A.VAL WHERE NOT EXISTS 
   (SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)

or

SELECT A.ABC_ID, A.VAL WHERE VAL NOT IN 
    (SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)

or

SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B 
    ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL WHERE B.VAL IS NULL

Please note that these queries to not require that ABC_ID be in table B at all. I think that does what you want.

Larry Lustig
The join will have the side effect of multipliyng records if the TableB has more than one record with matching ABC_ID and VAL
Remus Rusanu
Related: http://explainextended.com/2009/09/17/not-in-vs-not-exists-vs-left-join-is-null-oracle/
OMG Ponies
This does not work as Inner query returns you VAL for a different ABC_ID as well. E.g. Table B has values 1, 123, 1; 2, 123, 2, 3, 134, 5 and Table A has values 1, 123, 1; 2,123, 5; Ideally I want to get the Table A 2, 123, 5 to be returned
Fazal
Sorry ./.. The last query worked..Thanks
Fazal
Remus, the JOIN filters out the matching rows, so only table A rows that are not matched in table B will contribute to the result set. Because the rows that will show up are contributed solely from the table A side of the JOIN (through the LEFT OUTER), I think each row will show up once only.
Larry Lustig