diff --git a/mysql-test/r/cte_nonrecursive.result b/mysql-test/r/cte_nonrecursive.result index 54184f8aba1..207df07f083 100644 --- a/mysql-test/r/cte_nonrecursive.result +++ b/mysql-test/r/cte_nonrecursive.result @@ -961,3 +961,26 @@ show create view v1; View Create View character_set_client collation_connection v1 CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `v1` AS with alias1 as (select 1 AS `one`), alias2 as (select 2 AS `two`)select `alias1`.`one` AS `one`,`alias2`.`two` AS `two` from (`alias1` join `alias2`) latin1 latin1_swedish_ci drop view v1; +# +# MDEV-12440: the same CTE table is used in twice +# +create table t1 (a int, b varchar(32)); +insert into t1 values +(4,'aaaa' ), (7,'bb'), (1,'ccc'), (4,'dd'); +# cte2 is used in the main query and in the spec for ct3 +with +cte1 as (select * from t1 where b >= 'c'), +cte2 as (select * from cte1 where a < 7), +cte3 as (select * from cte2 where a > 1) +select * from cte2, cte3 where cte2.a = cte3.a; +a b a b +4 dd 4 dd +# cte2 is used twice in the spec for ct3 +with +cte1 as (select * from t1 where b >= 'b'), +cte2 as (select * from cte1 where b > 'c'), +cte3 as (select * from cte2 where a > 1 union select * from cte2 where a > 1) +select * from cte3; +a b +4 dd +drop table t1; diff --git a/mysql-test/t/cte_nonrecursive.test b/mysql-test/t/cte_nonrecursive.test index 700111d5507..bcdc06afbad 100644 --- a/mysql-test/t/cte_nonrecursive.test +++ b/mysql-test/t/cte_nonrecursive.test @@ -642,3 +642,27 @@ select * from v1; show create view v1; drop view v1; + +--echo # +--echo # MDEV-12440: the same CTE table is used in twice +--echo # + +create table t1 (a int, b varchar(32)); +insert into t1 values + (4,'aaaa' ), (7,'bb'), (1,'ccc'), (4,'dd'); + +--echo # cte2 is used in the main query and in the spec for ct3 +with +cte1 as (select * from t1 where b >= 'c'), +cte2 as (select * from cte1 where a < 7), +cte3 as (select * from cte2 where a > 1) +select * from cte2, cte3 where cte2.a = cte3.a; + +--echo # cte2 is used twice in the spec for ct3 +with +cte1 as (select * from t1 where b >= 'b'), +cte2 as (select * from cte1 where b > 'c'), +cte3 as (select * from cte2 where a > 1 union select * from cte2 where a > 1) +select * from cte3; + +drop table t1; \ No newline at end of file diff --git a/sql/sql_cte.cc b/sql/sql_cte.cc index 1dded86c824..d76ee13a010 100644 --- a/sql/sql_cte.cc +++ b/sql/sql_cte.cc @@ -780,6 +780,7 @@ st_select_lex_unit *With_element::clone_parsed_spec(THD *thd, with_table->next_global= spec_tables; } res= &lex->unit; + res->set_with_clause(owner); lex->unit.include_down(with_table->select_lex); lex->unit.set_slave(with_select);