diff --git a/src/Storages/MergeTree/KeyCondition.cpp b/src/Storages/MergeTree/KeyCondition.cpp index f5eeb4ed35c..2eea7a2f359 100644 --- a/src/Storages/MergeTree/KeyCondition.cpp +++ b/src/Storages/MergeTree/KeyCondition.cpp @@ -116,10 +116,20 @@ static void appendColumnNameWithoutAlias(const ActionsDAG::Node & node, WriteBuf { switch (node.type) { - case (ActionsDAG::ActionType::INPUT): [[fallthrough]]; - case (ActionsDAG::ActionType::COLUMN): + case (ActionsDAG::ActionType::INPUT): writeString(node.result_name, out); break; + case (ActionsDAG::ActionType::COLUMN): + { + /// If it was created from ASTLiteral, then result_name can be an alias. + /// We need to convert value back to string here. + if (const auto * column_const = typeid_cast(node.column.get())) + writeString(applyVisitor(FieldVisitorToString(), column_const->getField()), out); + /// It may be possible that column is ColumnSet + else + writeString(node.result_name, out); + break; + } case (ActionsDAG::ActionType::ALIAS): appendColumnNameWithoutAlias(*node.children.front(), out, legacy); break; diff --git a/tests/queries/0_stateless/02420_key_condition_actions_dag_bug_40599.reference b/tests/queries/0_stateless/02420_key_condition_actions_dag_bug_40599.reference new file mode 100644 index 00000000000..8bd1af11bf2 --- /dev/null +++ b/tests/queries/0_stateless/02420_key_condition_actions_dag_bug_40599.reference @@ -0,0 +1 @@ +2000 diff --git a/tests/queries/0_stateless/02420_key_condition_actions_dag_bug_40599.sql b/tests/queries/0_stateless/02420_key_condition_actions_dag_bug_40599.sql new file mode 100644 index 00000000000..4d2feacfde7 --- /dev/null +++ b/tests/queries/0_stateless/02420_key_condition_actions_dag_bug_40599.sql @@ -0,0 +1,10 @@ +create table tba (event_id Int64, event_dt Int64) Engine =MergeTree order by event_id ; +insert into tba select number%500, 20220822 from numbers(1e6); + +select count() from ( + SELECT event_dt FROM ( + select event_dt, 403 AS event_id from ( + select event_dt from tba as tba + where event_id = 9 and ((tba.event_dt >= 20220822 and tba.event_dt <= 20220822)) + ) + ) tba WHERE tba.event_dt >= 20220822 and tba.event_dt <= 20220822 and event_id = 403 );