diff --git a/mysql-test/r/derived_cond_pushdown.result b/mysql-test/r/derived_cond_pushdown.result index db65d9cfec9..c009a08b4f7 100644 --- a/mysql-test/r/derived_cond_pushdown.result +++ b/mysql-test/r/derived_cond_pushdown.result @@ -8672,3 +8672,40 @@ EXPLAIN } drop view v1,v2,v3; drop table t1,t2; +# +# MDEV-13166: pushdown from merged derived +# +CREATE TABLE t1 (i int) ENGINE=MyISAM; +INSERT INTO t1 VALUES (1),(2); +CREATE VIEW v1 AS SELECT MAX(i) AS f FROM t1; +SELECT * FROM ( SELECT * FROM v1 ) AS sq WHERE f > 0; +f +2 +explain format=json SELECT * FROM ( SELECT * FROM v1 ) AS sq WHERE f > 0; +EXPLAIN +{ + "query_block": { + "select_id": 1, + "table": { + "table_name": "", + "access_type": "ALL", + "rows": 2, + "filtered": 100, + "attached_condition": "v1.f > 0", + "materialized": { + "query_block": { + "select_id": 3, + "having_condition": "f > 0", + "table": { + "table_name": "t1", + "access_type": "ALL", + "rows": 2, + "filtered": 100 + } + } + } + } + } +} +DROP VIEW v1; +DROP TABLE t1; diff --git a/mysql-test/t/derived_cond_pushdown.test b/mysql-test/t/derived_cond_pushdown.test index 6b5da541b7d..beeaa7350f7 100644 --- a/mysql-test/t/derived_cond_pushdown.test +++ b/mysql-test/t/derived_cond_pushdown.test @@ -1509,3 +1509,20 @@ eval explain format=json $q4; drop view v1,v2,v3; drop table t1,t2; + +--echo # +--echo # MDEV-13166: pushdown from merged derived +--echo # + +CREATE TABLE t1 (i int) ENGINE=MyISAM; +INSERT INTO t1 VALUES (1),(2); +CREATE VIEW v1 AS SELECT MAX(i) AS f FROM t1; + +let $q= +SELECT * FROM ( SELECT * FROM v1 ) AS sq WHERE f > 0; + +eval $q; +eval explain format=json $q; + +DROP VIEW v1; +DROP TABLE t1; diff --git a/sql/item.cc b/sql/item.cc index 61a85f6d487..7ec50c2f472 100644 --- a/sql/item.cc +++ b/sql/item.cc @@ -7173,9 +7173,8 @@ Item *Item_direct_view_ref::derived_field_transformer_for_having(THD *thd, { st_select_lex *sel= (st_select_lex *)arg; table_map tab_map= sel->master_unit()->derived->table->map; - if (item_equal && !(item_equal->used_tables() & tab_map)) - return this; - if (!item_equal && used_tables() != tab_map) + if ((item_equal && !(item_equal->used_tables() & tab_map)) || + !item_equal) return this; return get_field_item_for_having(thd, this, sel); }