Skip to content

Commit

Permalink
Fix(optimizer): compute external columns for union sopes correctly (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
georgesittas authored Jan 19, 2024
1 parent d5a08b8 commit 8599903
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
11 changes: 8 additions & 3 deletions sqlglot/optimizer/scope.py
Original file line number Diff line number Diff line change
Expand Up @@ -323,9 +323,14 @@ def external_columns(self):
sources in the current scope.
"""
if self._external_columns is None:
self._external_columns = [
c for c in self.columns if c.table not in self.selected_sources
]
if isinstance(self.expression, exp.Union):
left, right = self.union_scopes
self._external_columns = left.external_columns + right.external_columns
else:
self._external_columns = [
c for c in self.columns if c.table not in self.selected_sources
]

return self._external_columns

@property
Expand Down
5 changes: 5 additions & 0 deletions tests/fixtures/optimizer/qualify_columns.sql
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,11 @@ SELECT (SELECT y.c AS c FROM y AS y) AS _col_0 FROM x AS x;
SELECT a FROM (SELECT a FROM x) WHERE a IN (SELECT b FROM (SELECT b FROM y));
SELECT _q_1.a AS a FROM (SELECT x.a AS a FROM x AS x) AS _q_1 WHERE _q_1.a IN (SELECT _q_0.b AS b FROM (SELECT y.b AS b FROM y AS y) AS _q_0);

# dialect: mysql
# execute: false
SELECT * FROM table_a as A WHERE A.col1 IN (SELECT MAX(B.col2) FROM table_b as B UNION ALL SELECT MAX(C.col2) FROM table_b as C);
SELECT * FROM table_a AS `A` WHERE `A`.col1 IN (SELECT MAX(`B`.col2) AS _col_0 FROM table_b AS `B` UNION ALL SELECT MAX(`C`.col2) AS _col_0 FROM table_b AS `C`);

--------------------------------------
-- Correlated subqueries
--------------------------------------
Expand Down

0 comments on commit 8599903

Please sign in to comment.