HelpMeWithXSLT
HelpMeWithXSLT

Reputation: 79

sql left join clarification

I have two tables.

I need all records from table A except where there is a match in table B, then take table B's matching value

So if table A has a match with table B, then I need to exclude that value from the results (i.e take all records from table A and replace records from table A with the matching value from table B).

from my understanding I left joined the two tables on the matching column and then added a where clause to exclude the null values but I'm not sure if that is correct.

data:

tableA (col1 =ID, col2 =value)
1, 5
2, 3
3, 7

tableB (col1 =ID, col2 =value)
4, 6
2, 9

expected result:

5

9

7

This is the closest I've gotten but I'm not sure if it's correct:

select * from tableA tblA
left join tableB tblB
on tblA.matchingColumn = tblB.matchingColumn
where tblB.matchingColumn is null

Upvotes: 0

Views: 45

Answers (2)

Pons
Pons

Reputation: 1111

This will return all the rows in TABLEA. If there are any matching value in TABLEB then it will be used as VALUE.

SELECT TBLA.ID
    , COALESCE(TBLB.VALUE, TBLA.VALUE) VALUE
FROM TABLEA TBLA
    LEFT JOIN TABLEB TBLB
        ON TBLA.ID = TBLB.ID;

UPDATE - SQLFiddle for this thread

Upvotes: 1

Gene Stempel
Gene Stempel

Reputation: 285

Perform a left join from tablea to tableb and use the value from a or b depending on match in tableb

select tablea.id, case when tableb.id is null then tablea.value else tableb.value end value
from tablea
left join tableb on tablea.id=tableb.id

Upvotes: 1

Related Questions