diff --git a/src/Interpreters/InterpreterSelectQuery.cpp b/src/Interpreters/InterpreterSelectQuery.cpp index 84de6fa4e6cf52789c49ce34c2ab438cd80b59a4..9f97160f77f1528f0430ad066fdbf24fbe8ccdee 100644 --- a/src/Interpreters/InterpreterSelectQuery.cpp +++ b/src/Interpreters/InterpreterSelectQuery.cpp @@ -784,9 +784,22 @@ static bool hasWithTotalsInAnySubqueryInFromClause(const ASTSelectQuery & query) { if (const auto * ast_union = query_table->as()) { + /// NOTE: Child of subquery can be ASTSelectWithUnionQuery or ASTSelectQuery, + /// and after normalization, the height of the AST tree is at most 2 for (const auto & elem : ast_union->list_of_selects->children) - if (hasWithTotalsInAnySubqueryInFromClause(elem->as())) - return true; + { + if (const auto * child_union = elem->as()) + { + for (const auto & child_elem : child_union->list_of_selects->children) + if (hasWithTotalsInAnySubqueryInFromClause(child_elem->as())) + return true; + } + else + { + if (hasWithTotalsInAnySubqueryInFromClause(elem->as())) + return true; + } + } } } diff --git a/tests/queries/0_stateless/01720_union_distinct_with_limit.reference b/tests/queries/0_stateless/01720_union_distinct_with_limit.reference new file mode 100644 index 0000000000000000000000000000000000000000..d00491fd7e5bb6fa28c517a0bb32b8b506539d4d --- /dev/null +++ b/tests/queries/0_stateless/01720_union_distinct_with_limit.reference @@ -0,0 +1 @@ +1 diff --git a/tests/queries/0_stateless/01720_union_distinct_with_limit.sql b/tests/queries/0_stateless/01720_union_distinct_with_limit.sql new file mode 100644 index 0000000000000000000000000000000000000000..9fc5b3eafd257f7afdfcdffa1b8a29f5c7422d06 --- /dev/null +++ b/tests/queries/0_stateless/01720_union_distinct_with_limit.sql @@ -0,0 +1,8 @@ +SELECT x +FROM +( + SELECT 1 AS x + UNION DISTINCT + SELECT 1 +) +LIMIT 1;