Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional JOIN Statement SQL Server

Is it possible to do the following:

IF [a] = 1234 THEN JOIN ON TableA  ELSE JOIN ON TableB 

If so, what is the correct syntax?

like image 586
J.S. Orris Avatar asked Oct 22 '14 22:10

J.S. Orris


People also ask

Can we add a condition on join?

To use the WHERE clause to perform the same join as you perform using the INNER JOIN syntax, enter both the join condition and the additional selection condition in the WHERE clause. The tables to be joined are listed in the FROM clause, separated by commas. This query returns the same output as the previous example.

What is conditional joining?

Using conditional JOIN syntax, you can establish joins based on conditions other than equality between fields. In addition, the host and cross-referenced join fields do not have to contain matching formats, and the cross-referenced field does not have to be indexed.

Can we use case in join condition in SQL Server?

@User632716 no unfortunately not!

Can we use or condition in join?

If you have an OR condition in the JOIN - and there is no possibility that the values in the OR statement overlap...then you can convert it to a UNION ALL. If the values overlap it would require a UNION which may not improve performance over the JOIN.


1 Answers

I think what you are asking for will work by joining the Initial table to both Option_A and Option_B using LEFT JOIN, which will produce something like this:

Initial LEFT JOIN Option_A LEFT JOIN NULL OR Initial LEFT JOIN NULL LEFT JOIN Option_B 

Example code:

SELECT i.*, COALESCE(a.id, b.id) as Option_Id, COALESCE(a.name, b.name) as Option_Name FROM Initial_Table i LEFT JOIN Option_A_Table a ON a.initial_id = i.id AND i.special_value = 1234 LEFT JOIN Option_B_Table b ON b.initial_id = i.id AND i.special_value <> 1234 

Once you have done this, you 'ignore' the set of NULLS. The additional trick here is in the SELECT line, where you need to decide what to do with the NULL fields. If the Option_A and Option_B tables are similar, then you can use the COALESCE function to return the first NON NULL value (as per the example).

The other option is that you will simply have to list the Option_A fields and the Option_B fields, and let whatever is using the ResultSet to handle determining which fields to use.

like image 103
simo.3792 Avatar answered Sep 19 '22 15:09

simo.3792