Ziouas
Ziouas

Reputation: 519

Getting matching attributes from two tables

I have two tables looking like this:

       A                        B
id_attr  value         id   id_attr  value
--------------         -------------------
  1        a            1       2       b
  2        b            1       3       c        
  3        c            2       2       b
  4       NULL          2       4       d
                        2       5       e
                        3       1       aaa
                        3       3       c

Table A is my reference table and I have multiple entries in table B. (every group of entries with the same id cosists of pairs of (id_attr,value) similiar to structure of table A). Goal is to check if entry in table A matches any of the entries in table B (one or more). One entry matches another when every attribute existing in table B under one id matches similiar attributes in table A. Also, in table A values could be NULL, but in table B not.

In example above my query should return "1", becouse only entries with id 1 fully match similiar entries in table A. Id 2 doesn't match, becouse in table A value of attribute 4 is NULL and it has an attribute which doesn`t exist in table A. Id 3 doesn't match either even if attribute 3 is similiar, but attribute 1 doesn't match.

As you can see to achieve a match not every one of the entries existing in table A should be matching, but if an attribute exists in table B then it value has to match similiar value in table A.

What is the most efficient way to achieve this result in an Oracle query?

Every help would be greatly appreciated. I can provide answers to further questions if I didn't express myself clear enough.

Upvotes: 0

Views: 3329

Answers (1)

vc 74
vc 74

Reputation: 38179

You can try the following:

SELECT ID, MIN(IS_OK) FROM
(
  SELECT B.ID ID, 
         DECODE(B.VALUE, A.VALUE, 'Y', 'N') IS_OK
  FROM A INNER JOIN B 
  ON B.ID_ATTR = A.ID_ATTR
)
GROUP BY ID;

Which will return you B's ID and a flag that indicates whether this ID is OK or not.

(Note that Decode will properly take care of the null values comparison without having to test for null values)

Upvotes: 3

Related Questions