Skip to content

Commit 64bd0ec

Browse files
authored
fix: agg input does not match union output when subquery (#17552)
* fix: agg input does not match union output when subquery Signed-off-by: Kould <[email protected]> * test: add fix case on subquery.test Signed-off-by: Kould <[email protected]> --------- Signed-off-by: Kould <[email protected]>
1 parent c2ea7a6 commit 64bd0ec

File tree

3 files changed

+37
-2
lines changed

3 files changed

+37
-2
lines changed

src/query/sql/src/planner/optimizer/decorrelate/decorrelate.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -286,7 +286,7 @@ impl SubqueryRewriter {
286286
)?;
287287

288288
let mut join_type = JoinType::LeftSingle;
289-
if subquery.contain_agg.unwrap() {
289+
if matches!(subquery.contain_agg, Some(true)) {
290290
let rel_expr = RelExpr::with_s_expr(&subquery.subquery);
291291
let card = rel_expr
292292
.derive_cardinality()?
@@ -473,7 +473,9 @@ impl SubqueryRewriter {
473473
.table_index(column_entry.table_index())
474474
.build(),
475475
});
476-
let derive_column = self.derived_columns.get(correlated_column).unwrap();
476+
let Some(derive_column) = self.derived_columns.get(correlated_column) else {
477+
continue;
478+
};
477479
let column_entry = metadata.column(*derive_column);
478480
let left_column = ScalarExpr::BoundColumnRef(BoundColumnRef {
479481
span,

src/query/sql/src/planner/optimizer/decorrelate/flatten_plan.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -786,6 +786,9 @@ impl SubqueryRewriter {
786786
flatten_info,
787787
need_cross_join,
788788
)?;
789+
self.derived_columns
790+
.retain(|_, derived_column| op.output_indexes.contains(derived_column));
791+
789792
Ok(SExpr::create_binary(
790793
Arc::new(op.clone().into()),
791794
Arc::new(left_flatten_plan),

tests/sqllogictests/suites/query/subquery.test

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -912,3 +912,33 @@ group by input_date order by input_date;
912912

913913
statement ok
914914
drop table test_group;
915+
916+
# https://github.com/databendlabs/databend/issues/17476
917+
statement ok
918+
DROP TABLE IF EXISTS t1;
919+
920+
statement ok
921+
DROP TABLE IF EXISTS t2;
922+
923+
statement ok
924+
CREATE TABLE t1 (i1 INT);
925+
926+
statement ok
927+
CREATE TABLE t2 (i1 INT);
928+
929+
statement ok
930+
insert into t1 values (0);
931+
932+
statement ok
933+
insert into t2 values (0);
934+
935+
query I
936+
SELECT 1 FROM t1
937+
WHERE t1.i1 = (
938+
SELECT t1.i1
939+
FROM t2 UNION
940+
SELECT dt1.i1
941+
FROM (t1 AS dt1)
942+
);
943+
----
944+
1

0 commit comments

Comments
 (0)