Question

How this queries will be evaluated? (what i ask is: what will be the logic that the db-engine will use to gather the data?)?

A:

SELECT tableA.* FROM tableA
LEFT JOIN tableB ON tableB.key1 = tableA.key1
INNER JOIN tableC ON tableC.key2 = tableB.key2

B:

SELECT tableA.* FROM tableA
INNER JOIN tableC 
LEFT JOIN tableB
ON (tableB.key1 = tableA.key1) AND (tableC.key2 = tableB.key2)

C:
What is the syntax, for joining multiple tables? (A and B for example)

D:
What is the logic behind the order of joins?
(How different joins (left, and inner) should be combines in a query?)

ANY-one?

Was it helpful?

Solution

SELECT tableA.* FROM tableA
LEFT JOIN tableB ON tableB.key1 = tableA.key1
INNER JOIN tableC ON tableC.key2 = tableB.key2

Since no brackets are used this should be evaluated left-to-right, so:

SELECT tableA.* 
FROM 
(tableA LEFT JOIN tableB ON tableB.key1 = tableA.key1)
        INNER JOIN tableC ON tableC.key2 = tableB.key2

Meaning you first select all records from table A, with the matching records from B if they exist (outer join). That result set is then joined with C, but since you join on B.Key, all previous records where B = null will now disappear. I am quite sure that the first join could be an inner join, giving the same result.

SELECT tableA.* FROM tableA
INNER JOIN tableC 
LEFT JOIN tableB
ON (tableB.key1 = tableA.key1) AND (tableC.key2 = tableB.key2)

Now we first cross-join every record from A with every record from C (cartesian product). That (possibly huge and possibly meaningless) resultset we extend with data from B where we can find it (meaning we add a record from B wherever we have a match with either A or B).

In general, when joining several tables, just take it step by step and always try to realize what you are joining with what. When in doubt, use brackets :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top