Nested joins #1859
-
Hey Guys, Im currently taking a look at nested joins, so for example:
In the query above a INNER JOIN is performed first between table b and c, and then a LEFT JOIN is performed with that set. Currently the AST is as like:
I would however expect something like this:
The AST above however loses the parenthesis in case its generated:
Im thinking about have it parsing like the second AST and than in generation of the SQL it would create the parenthesis in case the join entity has underlying joins as well. So in this case the table b has joins on itself, therefore parenthesis would be required at the join between table b and c. This way such AST's can be optimized as well, because i got errors while optimizing due to directly having a table reference in a subquery, while a select for example is expected there. What do you guys think? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
Hey Sebastiaan :) I agree that the current form of the AST is a bit awkward,
Why does it lose the parentheses? I can't reproduce this: >>> import sqlglot
>>>
>>> sqlglot.transpile("""
... SELECT
... a.id
... ,b.test
... ,c.test2
... FROM a
... LEFT JOIN (
... b
... INNER JOIN c
... ON c.id = b.id
... )
... ON b.id = a.id
... """, "postgres")
['SELECT a.id, b.test, c.test2 FROM a LEFT JOIN (b INNER JOIN c ON c.id = b.id) ON b.id = a.id']
This might be a bug on our side. I recently implemented a transformation in sqlglot/sqlglot/optimizer/qualify_tables.py Lines 46 to 50 in 146dc34 Do you have a query that fails to be optimized? |
Beta Was this translation helpful? Give feedback.
-
Hey George, Thanks for your response. Well actually the table class does have a property "joins", however it does not seem supported by the optimizer.
Btw the nested join can also be written without the parenthesis, like:
That also results in an error however on parsing I think using the joins arg at the the table class would be nicest here as it is actually related to that table. However subqueries do not have this arg yet. So that would involve adjusting the parser so those nested joins are part of the joins arg at the exp.Table/exp.Subquery and adjusting the scope class so those joins are included. What do you think? |
Beta Was this translation helpful? Give feedback.
Fixed in 156afcd and 3a8f230.