Wednesday 5 September 2018

Mysql Right Join works, Inner Join works, Left join does not? Why?

I have some SQL joining multiple tables in Access. When attempting to run it, I get an error in the "JOIN" (specifically "JOIN expression not supported"). I believe I have narrowed down the problem to one join but why it isn't working doesn't make any sense to me. The original full SQL FROM clause is thus:

FROM  (
     (
      Customers RIGHT JOIN
            (
            Sales LEFT JOIN SaleType ON Sales.SalesForID = SaleType.SalesForID
            )
      ON Customers.CustomerID = Sales.CustomerID
     ) LEFT JOIN
          (
           StudentContracts LEFT JOIN
               (
               StudentsClasses INNER JOIN Classes ON StudentsClasses.ClassID = Classes.ClassID
                )
            ON StudentContracts.CustomerID = StudentsClasses.CustomerID
           )
       ON Customers.CustomerID = StudentContracts.CustomerID
 )

The part I believe the query fails is on this "LEFT" join:
(
  StudentContracts LEFT JOIN
          (
          StudentsClasses INNER JOIN Classes ON StudentsClasses.ClassID = Classes.ClassID
          )
   ON StudentContracts.CustomerID = StudentsClasses.CustomerID
)

I've tried switching the the "LEFT" to an "INNER" and it works. I've switched it to a "RIGHT" and it works. Why will it not work for a "LEFT" join but work for the others? What I need is a result showing the records in joined "Classes" table linked to the StudentContracts but also the StudentContracts without a record in the Classes table. As per the answer on this post: Difference between left join and right join in SQL Server I am fairly certain I want a left join and this should work.
What am I missing here?

You have far too many parentheses and things are not in the right order. It would be easiest to build this in the query design window of MS Access, and then everything will be generated for you, you can switch to SQL view to see.
For example, the above should read something like:
SELECT *
FROM (Customers
RIGHT JOIN Sales
ON Customers.CustomerID = Sales.CustomerID)
LEFT JOIN SaleType
ON Sales.SalesForID = SaleType.SalesForID

It is the convention that RIGHT JOIN is avoided because they can easily be written as LEFT JOIN, so it avoids any confusion.

0 comments:

Post a Comment