0

I'm trying to join a table on a column

Select * From tableA a LEFT JOIN tableB b ON a.key = b.foreignkey ... 

If that row cannot be found I want to join it to another column in table B. Is there an efficient way to do this.

Thanks

2 Answers 2

1

You can use COALESCE to join on the first non-NULL column.

Select * From tableA a LEFT JOIN tableB b ON a.key = COALESCE(b.foreignkey, b.another_column, b.another_column2) 

It will try to join with b.foreignkey first. if that is NULL then b.foreignkey and so on.

Please find the example here.

Sign up to request clarification or add additional context in comments.

Comments

1

Add another LEFT JOIN:

Select * From tableA a left join tableB b on a.key = b.foreignkey left join tableC c on a.key = c.foreignkey and b.foreignkey is null; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.