I’m trying to join 4 tables, two 1-N ones and one through an N-N table. Strangely mySql doesn’t seem to like one of my syntaxes. Does anybody know if this is due to myOwn limitations or mySql?
This doesn’t work:
SELECT *
FROM tableOne t1 JOIN tableTwo t2
LEFT OUTER JOIN N_N_tableThree t3
JOIN tableFour t4 ON t4.id = t3.fk_tableFour
ON t2.id = t3.fk_tableTwo
ON t2.id = t1.fk_tableTwo
While this does work
SELECT *
FROM tableOne t1,
tableTwo t2 LEFT OUTER JOIN N_N_tableThree t3
JOIN tableFour t4 ON t4.id = t3.tableFour_id
ON t2.id = t3.tableTwo_id
WHERE t2.id = t1.tableTwo_id
Anybody a clue?
Thanks for answering.
Use this syntax instead:
This will be equivalent of the second query that worked.
Because the
WHERE t2.id = t1.tableTwo_idin the second query is actually anINNER JOIN1, which will be the same asINNER JOIN tableTwo t2 ON t2.id = t1.fk_tableTwoas I did. This is the oldJOINsyntax, try to avoid it and use the ANSI SQL-92 syntax instead as I did. For more information see this:The query you posted didn’t work, because it is not the correct syntax for
JOINin MySQL, you have threeONclauses after each others:Each
JOINshould has the join condition specified with theONclause after theJOINdirectly, if not it would a cross join2. But not multipleON‘s the way you did.SQL Fiddle Demo
1: Don’t be confused with the use of
INNER JOINinstead ofJOINthey are the same the defaultJOINis inner join, I just I used for readability. Also, the same thing with theOUTERkeyword, I omit it inLEFT JOINsince it is optional when usingLEFTorRIGHT2: You will find other variations of the
JOINsyntax in MySQL in the reference page, like theJOIN tablenamewithout a join condition, and others. You might need to read them.