今天有人問我一個物化視圖查詢重寫的問題,最後發現問題其實和物化視圖的功能沒有多大的關係,而是隱式轉換導致的問題。
還是通過例子來說明這個問題:
SQL> create table t (
2 id number,
3 time date,
4 other varchar2(4000))
5 partition by range (time)
6 (partition p1 values less than (to_date('2008-1-1', 'yyyy-mm-dd')),
7 partition p2 values less than (to_date('2009-1-1', 'yyyy-mm-dd')),
8 partition p3 values less than (to_date('2010-1-1', 'yyyy-mm-dd')),
9 partition p4 values less than (to_date('2011-1-1', 'yyyy-mm-dd')));
Table created.
SQL> insert into t
2 select rownum, sysdate - rownum, lpad('a', 4000, 'a')
3 from dba_objects;
76162 rows created.
SQL> create materialized view log on t
2 with rowid, sequence
3 (id, time)
4 including new values;
Materialized view log created.
SQL> create materialized view mv_t
2 refresh fast
3 enable query rewrite as
4 select time, count(*)
5 from t
6 group by time;
Materialized view created.
下面看看物化視圖是否可以查詢重寫:
SQL> set autot on exp
SQL> select time, count(*)
2 from t
3 where time > to_date('2009-1-1', 'yyyy-mm-dd')
4 and time < to_date('2009-1-10', 'yyyy-mm-dd')
5 group by time;
TIME COUNT(*)
-------------- ----------
04-1月-09 1
09-1月-09 1
01-1月-09 1
05-1月-09 1
03-1月-09 1
02-1月-09 1
08-1月-09 1
07-1月-09 1
06-1月-09 1
9 rows selected.
Execution Plan
----------------------------------------------------------
Plan hash value: 1712400360
-------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
-------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 9 | 198 | 33 (4)| 00:00:01 |
|* 1 | MAT_VIEW REWRITE ACCESS FULL| MV_T | 9 | 198 | 33 (4)| 00:00:01 |
-------------------------------------------------------------------------------------
Predicate Information (identified by operation id):