Search code examples
sqljoinleft-joinright-join

Right and Left Join Together in SQL


I am trying to use a RIGHT and LEFT Join together. I have it working when only left joining one table. But I am trying to now include another table in my left join. It gives me an error saying I am missing an operator. Where am I missing a parenthesis?

FROM qSplit RIGHT JOIN (t_i360_agent AS i LEFT JOIN cmsAgent_Split AS c 
ON ((i.LocalDay = c.LocalDay) AND (i.ACDID = c.LOGID)) 
LEFT JOIN qry_AllNewtables as qry ON (qry.custConvDate = c.LocalDay)
AND (qry.CustAgentLoginName = i.Loginname)  ) ON qSplit.SPLIT = c.SPLIT

Solution

  • Don't use LEFT JOIN and RIGHT JOIN together. I imagine that somewhere there could be a query where it makes sense. In practice, I don't think I have ever used them both in the same query, possibly because I write queries using LEFT JOIN.

    If you want everything in the agent table, then make it first! And use left join;

    FROM t_i360_agent i LEFT JOIN
         cmsAgent_Split c 
         ON i.LocalDay = c.LocalDay AND i.ACDID = c.LOGID LEFT JOIN 
         qry_AllNewtables qry
         ON qry.custConvDate = c.LocalDay AND 
            qry.CustAgentLoginName = i.Loginname LEFT JOIN
         qSplit
         ON qSplit.SPLIT = c.SPLIT
    

    It is much easier to follow the intention of the query this way. You are starting with the data that you think is so important that you want to keep all of it, even when JOINs have no matching rows.