Commit a4e58882 authored by Varun Gupta's avatar Varun Gupta

MDEV-18431: Select max + row_number giving incorrect result

The issue here was when we had a subquery and a window function in an expression in
the select list then subquery was getting computed after window function computation.
This resulted in incorrect results because the subquery was correlated and the fields
in the subquery was pointing to the base table instead of the temporary table.

The approach to fix this was to have an additional field in the temporary table
for the subquery and to execute the subquery before window function execution.
After execution the values for the subquery were stored in the temporary table
and then when we needed to calcuate the expression, all we do is read the values
from the temporary table for the subquery.
parent f72760df
......@@ -3488,3 +3488,20 @@ ifnull(max(n1) over (partition by n1),'aaa')
4
drop table t1;
drop view v1;
#
# MDEV-18431: Select max + row_number giving incorrect result
#
create table t1 (id int, v int);
insert into t1 values (1, 1), (1,2), (1,3), (2, 1), (2, 2);
select e.id,
(select max(t1.v) from t1 where t1.id=e.id) as a,
row_number() over (partition by e.id order by e.v) as b,
(select max(t1.v) from t1 where t1.id=e.id) + (row_number() over (partition by e.id order by e.v)) as sum_a_b
from t1 e;
id a b sum_a_b
1 3 1 4
1 3 2 5
1 3 3 6
2 2 1 3
2 2 2 4
drop table t1;
......@@ -2240,3 +2240,17 @@ explain select * from v1;
select * from v1;
drop table t1;
drop view v1;
--echo #
--echo # MDEV-18431: Select max + row_number giving incorrect result
--echo #
create table t1 (id int, v int);
insert into t1 values (1, 1), (1,2), (1,3), (2, 1), (2, 2);
select e.id,
(select max(t1.v) from t1 where t1.id=e.id) as a,
row_number() over (partition by e.id order by e.v) as b,
(select max(t1.v) from t1 where t1.id=e.id) + (row_number() over (partition by e.id order by e.v)) as sum_a_b
from t1 e;
drop table t1;
......@@ -1996,7 +1996,6 @@ void Item::split_sum_func2(THD *thd, Ref_ptr_array ref_pointer_array,
}
if (unlikely((!(used_tables() & ~PARAM_TABLE_BIT) ||
type() == SUBSELECT_ITEM ||
(type() == REF_ITEM &&
((Item_ref*)this)->ref_type() != Item_ref::VIEW_REF))))
return;
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment