What's the best option for joining using multiple columns

时间:2018-01-15 18:11:21

标签: sql oracle

I have the below tables

TableA

ID     ID2
 1     101
 2     102
 3     103
       104
 5

TableB

ID     ID2
 1     101
 2     102
 3     103
       104
 5

I need to join on either ID or ID2. What's the right approach here, utilizing an 'OR' condition?

SELECT *
FROM TABLEA A
INNER JOIN TABLEB B ON A.ID = B.ID OR A.ID2 = B.ID2

1 个答案:

答案 0 :(得分:4)

Your method works. However, or can kill performance in joins, so you might want two left joins:

SELECT *
FROM TABLEA A LEFT JOIN
     TABLEB Bid
     ON A.ID = Bid.ID LEFT JOIN
     TABLEB Bid2
     ON a.ID2 = Bid2.ID2 AND Bid.id IS NULL;

You then have to be careful about what you select -- making judicious use of COALESCE() to get the columns from the table you really wan