I need to JOIN a table when certain conditions are met and LEFT JOIN it when other conditions are met. Since I am in a MS Dynamic CRM with filters, I can’t use UNION
SELECT stuff.stuffs
FROM MainTable
JOINS othertable
LEFT JOIN othertables
LEFT JOIN TableX as X1 ON (Conditions1.1 = X1.1
AND MainTable.Type = 1)
JOIN TableX as X2 ON (Conditions2.2 = X2.2
AND MainTable.Type = 2)
- If I comment out the X2 part, I get what I need from the X1 part and nothing from the X2.
- If I LEFT JOIN the X2 part, I have extra information in X2.
- If I leave it as such, I get what I need from the X2 part, but nothing from X1.
I tried a few variants, but I can’t reach a satisfactory solution.
EDIT: My original query was as such:
SELECT stuff.stuffs
FROM MainTable
(LEFT) JOIN TableX as X1
ON (Conditions1.1 = X1.1
AND MainTable.Type = 1)
OR
ON (Conditions2.2 = X2.2
AND MainTable.Type = 2)
But if it is as left join, I get extra info from X2
and a JOIN give me missing info from X1,
The actual matching needed is not clear in the OP, but you could try something like:
Given what you have added to the OP and in comments, it is still not clear whether you seek rows from TableX that satisfy either condition or one and only one of the conditions. However, for completeness here’s both:
Either condition: My original solution above and the solution you added to your post.
One and only one of the conditions:
What is missing from the original post is any notion of foreign keys references from TableX to MainTable. Thus, typically, I would have thought something like: