**How to reproduce**
Clickhouse version 21.2-21.3

```
SELECT x
FROM
(
    SELECT 1 AS x
    UNION DISTINCT
    SELECT 1
)
LIMIT 1

Query id: b82bbb8d-dea9-4f1c-9a2f-5b0e9b6c2422


0 rows in set. Elapsed: 0.002 sec.

Received exception from server (version 21.2.3):
Code: 49. DB::Exception: Received from localhost:9000. DB::Exception: Bad cast from type DB::ASTSelectWithUnionQuery to DB::ASTSelectQuery.
```


/** There are no limits on the maximum size of the result for the subquery.
  *  Since the result of the query is not the result of the entire query.
  */
static Context getSubqueryContext(const Context & context)
{
    Context subquery_context = context;
    Settings subquery_settings = context.getSettings();
    subquery_settings.max_result_rows = 0;
    subquery_settings.max_result_bytes = 0;
    
    subquery_settings.extremes = false;
    subquery_context.setSettings(subquery_settings);
    return subquery_context;
}
static void rewriteMultipleJoins(ASTPtr & query, const TablesWithColumns & tables, const String & database)
{
    ASTSelectQuery & select = query->as<ASTSelectQuery &>();
    Aliases aliases;
    if (ASTPtr with = select.with())
        QueryAliasesNoSubqueriesVisitor(aliases).visit(with);
    QueryAliasesNoSubqueriesVisitor(aliases).visit(select.select());
    CrossToInnerJoinVisitor::Data cross_to_inner{tables, aliases, database};
    CrossToInnerJoinVisitor(cross_to_inner).visit(query);
    JoinToSubqueryTransformVisitor::Data join_to_subs_data{tables, aliases};
    JoinToSubqueryTransformVisitor(join_to_subs_data).visit(query);
}
static void checkAccessRightsForSelect(