diff --git a/datafusion/core/src/physical_plan/subquery.rs b/datafusion/core/src/physical_plan/subquery.rs index 86cb3b2dcc52..e6b2c9f786c5 100644 --- a/datafusion/core/src/physical_plan/subquery.rs +++ b/datafusion/core/src/physical_plan/subquery.rs @@ -22,6 +22,7 @@ use arrow::compute::concat; use std::any::Any; +use std::collections::HashMap; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; @@ -61,16 +62,14 @@ impl SubqueryExec { input: Arc, cursor: Arc, ) -> Result { - let input_schema = (*input.schema()).clone(); + let input_schema = input.schema(); - let merged_schema = Schema::try_merge( - vec![input_schema].into_iter().chain( - subqueries - .iter() - .map(|s| (*s.schema()).clone()) - .collect::>(), - ), - )?; + let mut total_fields = input_schema.fields().clone(); + for q in subqueries.iter() { + total_fields.append(&mut q.schema().fields().clone()); + } + + let merged_schema = Schema::new_with_metadata(total_fields, HashMap::new()); if merged_schema.fields().len() != input.schema().fields().len() + subqueries.len() diff --git a/datafusion/core/src/sql/planner.rs b/datafusion/core/src/sql/planner.rs index 2bb928e10b42..ba707259fa28 100644 --- a/datafusion/core/src/sql/planner.rs +++ b/datafusion/core/src/sql/planner.rs @@ -2060,7 +2060,9 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> { SQLExpr::Subquery(q) => { let with_outer_query_context = self.with_context(|c| c.outer_query_context_schema.push(Arc::new(schema.clone()))); - let plan = with_outer_query_context.query_to_plan(*q)?; + let alias_name = format!("subquery-{}", self.context.subqueries_plans().unwrap_or_default().unwrap_or_default().len()); + let plan = with_outer_query_context.query_to_plan_with_alias(*q, Some(alias_name), &mut HashMap::new())?; + let fields = plan.schema().fields(); if fields.len() != 1 { return Err(DataFusionError::Plan(format!("Correlated sub query requires only one column in result set but found: {:?}", fields)));