简体   繁体   中英

SQL JOIN and LEFT JOIN the same table with differents conditions

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,

I'm thinking you need to try this instead:

   SELECT stuff.stuffs
     FROM TABLEX x
LEFT JOIN MAINTABLE mt1 ON mt.1 = x.1
                       AND mt.type = 1
LEFT JOIN MAINTABLE mt2 ON mt.2 = x.2
                       AND mt.type = 2

The actual matching needed is not clear in the OP, but you could try something like:

Select stuff.stuffs
From MainTable
    Left Join TableX As X1
        On ( MainTable.Type = 1 And X1.1 = ...)
            Or ( MainTable.Type = 2 And X1.2 = ...)

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:

Select stuff.stuffs
From MainTable
    Left Join TableX As X1
        On X1.1 = ...
    Left Join TableX As X2
        On X2.2 = ...
Where ( MainTable.Type = 1 And X1.PK Is Not Null And X2.PK Is Null )
    Or ( MainTable.Type = 2 And X2.PK Is Not Null And X1.PK Is Null )

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:

Select stuff.stuffs
From MainTable
    Left Join TableX As X1
        On X1.FK = MainTable.PK
    Left Join TableX As X2
        On X2.FK = MainTable.PK
Where ( MainTable.Type = 1 And X1.Col1 = ...  And X2.PK Is Null )
    Or ( MainTable.Type = 2 And X2.Col1 = ... And X1.PK Is Null )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM