silundong commented on code in PR #4691:
URL: https://github.com/apache/calcite/pull/4691#discussion_r2629267265


##########
core/src/main/java/org/apache/calcite/sql2rel/RelFieldTrimmer.java:
##########
@@ -634,7 +634,23 @@ public TrimResult trimFields(
     RelOptUtil.InputFinder inputFinder =
         new RelOptUtil.InputFinder(inputExtraFields, fieldsUsed);
     conditionExpr.accept(inputFinder);
-    final ImmutableBitSet inputFieldsUsed = inputFinder.build();
+
+    // Collect all the SubQueries in the filter condition.
+    List<RexSubQuery> subQueries = RexUtil.SubQueryCollector.collect(filter);
+    // Get all the correlationIds present in the SubQueries
+    Set<CorrelationId> correlationIds = 
RelOptUtil.getVariablesUsed(subQueries);
+    ImmutableBitSet requiredColumns = ImmutableBitSet.of();
+    if (!correlationIds.isEmpty()) {
+      // Correlation columns are also needed by SubQueries, so add them to 
inputFieldsUsed.
+      requiredColumns = 
RelOptUtil.correlationColumns(correlationIds.iterator().next(), filter);

Review Comment:
   I'm not sure if this works correctly when nested correlations. 
`RelOptUtil.getVariablesUsed` will return all CorrelationIds except those 
generated within the subquery, so `correlationIds` may be have multiple 
elements. For example:
   ```
   select deptno, right_q.ename from emp e1, LATERAL (
       select ename from emp e2 where exists(
           select * from emp e3 where e1.sal = e3.sal and e2.empno = e3.empno)) 
right_q
   
   LogicalProject(DEPTNO=[$7], ENAME=[$8])
     LogicalCorrelate(correlation=[$cor0], joinType=[inner], 
requiredColumns=[{5}])
       LogicalTableScan(table=[[scott, EMP]])
       LogicalProject(ENAME=[$1])
         LogicalFilter(condition=[EXISTS({       <--------
   LogicalFilter(condition=[AND(=($cor0.SAL, $5), =($cor1.EMPNO, $0))])
     LogicalTableScan(table=[[scott, EMP]])
   })], variablesSet=[[$cor1]])
           LogicalTableScan(table=[[scott, EMP]])
   ```
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to