Search code examples
sqlsql-serverssmsqsqlquery

Can someone help me with this join statment in SQL? There are two JOINS after each other


In the image below ([2]) on line 20 you see "LEFT JOIN HUB_EMPLOYEES HM" and immediately after a join on LINK_EMPLOYEES.

What is the HUB_EMPLOYEES left joined on? The join on LINK_EMPLOYEES is specified on line 21, but I don't see how the left join on HUB_EMPLOYEES works.

If someone could explain this I would greatly appreciate it, I couldn't find the answer elsewhere.

Relational Diagram image

This is the code:

SELECT HE.EMPLOYEE_SEQNR, HE.EMPLOYEEID, SE.LASTNAME AS EMPLASTNAME,
       isnull(SM.LASTNAME, 'DIRECTOR') AS MNGLASTNAME, 
       SE.TITLE, SE.COUNTRY, SE.REGION, SE.CITY, SE.POSTALCODE 
FROM SAT_EMPLOYEES SE 
JOIN      HUB_EMPLOYEES HE ON SE.EMPLOYEE_SEQNR = HE.EMPLOYEE_SEQNR
LEFT JOIN HUB_EMPLOYEES HM
JOIN      LINK_EMPLOYEES ON HM.EMPLOYEE_SEQNR = LINK_EMPLOYEES.MANAGER_SEQNR
JOIN      SAT_EMPLOYEES SM ON HM.EMPLOYEE_SEQNR = SM.EMPLOYEE_SEQNR
ON HE.EMPLOYEE_SEQNR = LINK_EMPLOYEES.EMPLOYEE_SEQNR

Solution

  • It's equivalent to:

    SELECT HE.EMPLOYEE_SEQNR, HE.EMPLOYEEID, SE.LASTNAME AS EMPLASTNAME,
           isnull(SubQ.LASTNAME, 'DIRECTOR') AS MNGLASTNAME, 
           SE.TITLE, SE.COUNTRY, SE.REGION, SE.CITY, SE.POSTALCODE 
    FROM    SAT_EMPLOYEES SE 
    JOIN      HUB_EMPLOYEES HE ON SE.EMPLOYEE_SEQNR = HE.EMPLOYEE_SEQNR
    LEFT JOIN (
                    SELECT  LINK_EMPLOYEES.EMPLOYEE_SEQNR
                    ,       SM.LASTNAME
                    FROM    HUB_EMPLOYEES HM
                    JOIN      LINK_EMPLOYEES ON HM.EMPLOYEE_SEQNR = LINK_EMPLOYEES.MANAGER_SEQNR
                    JOIN      SAT_EMPLOYEES SM ON HM.EMPLOYEE_SEQNR = SM.EMPLOYEE_SEQNR
            ) SubQ
    ON HE.EMPLOYEE_SEQNR = SubQ.EMPLOYEE_SEQNR
    

    Personally I don't like that syntax, because it isn't very intuitive.