I don’t understand why this query works and what it actually means. It should be noted that this query works when using PDO but doesn’t through Mysql cli or even phpmyadmin.
SELECT table1.something, table2.something
FROM someTable
LEFT JOIN table 1
INNER JOIN table2
ON table2.table1_id = table1.id
ON table1.account_id = someTable.account_id
No errors are thrown and, even weirder, I actually have results that are coherent with what the query is supposed to do.
2
Answers
This is valid SQL syntax, assuming you have just taken a snippet from the
FROM
clause. It is interpreted as:That said, this is really arcane, because the alias renames
table2
tobbm
, which is not used. TheON
conditions are only referring to earlier tables. The result is some strange form ofCROSS JOIN
.That you can nest
JOIN
s this way should — in my opinion — be merely viewed as an amusement. Don’t nestJOIN
s. EachJOIN
should be followed by its very ownON
clause, before the next table/subquery reference. Nesting joins makes the code is harder to understand. It can introduce errors (which I think happened in this case). There can also be subtle edge cases where it is a little challenging to figure out what is happening.There are two syntax variations in Standard SQL for writing multiple joins, the common one:
and the strange one:
In both cases the first ON is processed first, which means the strange syntax joins the first table in the last ON and the last table in the first ON, which is really hard to follow. That’s why almost nobody is using it (but some tools might create it)
To change your strange
to the common one move the last ON after the first join: