diff --git a/sqlglot/optimizer/merge_subqueries.py b/sqlglot/optimizer/merge_subqueries.py index 603f5df0c4..866f78c239 100644 --- a/sqlglot/optimizer/merge_subqueries.py +++ b/sqlglot/optimizer/merge_subqueries.py @@ -227,10 +227,13 @@ def _rename_inner_sources(outer_scope, inner_scope, alias): inner_scope (sqlglot.optimizer.scope.Scope) alias (str) """ - taken = set(outer_scope.selected_sources) - conflicts = taken.intersection(set(inner_scope.selected_sources)) + inner_taken = set(inner_scope.selected_sources) + outer_taken = set(outer_scope.selected_sources) + conflicts = outer_taken.intersection(inner_taken) conflicts -= {alias} + taken = outer_taken.union(inner_taken) + for conflict in conflicts: new_name = find_new_name(taken, conflict) diff --git a/tests/fixtures/optimizer/merge_subqueries.sql b/tests/fixtures/optimizer/merge_subqueries.sql index ce5a435119..e39e7d1709 100644 --- a/tests/fixtures/optimizer/merge_subqueries.sql +++ b/tests/fixtures/optimizer/merge_subqueries.sql @@ -446,3 +446,21 @@ SELECT 1 AS a; WITH q AS (SELECT x.a AS a FROM x AS x ORDER BY x.a) SELECT q.a AS a FROM q AS q UNION ALL SELECT 1 AS a; +# title: Consecutive inner - outer conflicting names +WITH tbl AS (select 1 as id) +SELECT + id +FROM ( + SELECT OTBL.id + FROM ( + SELECT OTBL.id + FROM ( + SELECT OTBL.id + FROM tbl AS OTBL + LEFT OUTER JOIN tbl AS ITBL ON OTBL.id = ITBL.id + ) AS OTBL + LEFT OUTER JOIN tbl AS ITBL ON OTBL.id = ITBL.id + ) AS OTBL + LEFT OUTER JOIN tbl AS ITBL ON OTBL.id = ITBL.id +) AS ITBL; +WITH tbl AS (SELECT 1 AS id) SELECT OTBL.id AS id FROM tbl AS OTBL LEFT OUTER JOIN tbl AS ITBL_2 ON OTBL.id = ITBL_2.id LEFT OUTER JOIN tbl AS ITBL_3 ON OTBL.id = ITBL_3.id LEFT OUTER JOIN tbl AS ITBL ON OTBL.id = ITBL.id;