时间复杂度可能是 O(n)。
这个问题是询问“此查询将使用索引扫描还是全表扫描?”的另一种方式。通常,在查找一小部分行时,索引范围扫描效果更好。而且,一般来说,在查找大部分行时,全表扫描效果更好。
没有一个“神奇的数字”。但根据我的经验,对于任何显着大小的表,25% 肯定是在全表扫描区域中。
这个决定取决于很多因素:缓存、多块读取计数、物理存储、统计信息(对象和系统)、集群因素(行在磁盘上的存储情况——因为 Oracle 一次检索一个块的数据一个查询可能需要读取 100% 的块才能读取 1% 的数据)等。
代码示例
这里有一个简单的示例演示全表扫描。请注意,我使用的是 100000 行。如果问题是关于只有少数行的表,那么时间复杂度无关紧要,因为恒定开销将比算法更重要。
create table RealEstate
(
ID DEC(10),
Type VARCHAR(40),
Price DEC(10,2),
the_Size DEC(4)
);
create index RealEstate_idx on RealEstate(type);
insert into RealEstate
select level, decode(mod(level, 4), 0, 'Apartment', 1, 'House', 2, 'Townhouse', 3, 'Villa') , 100, 100
from dual connect by level <= 100000;
begin
dbms_stats.gather_table_stats(user, 'realestate');
end;
/
执行计划
注意TABLE ACCESS FULL。
explain plan for select * from RealEstate where type = 'House';
select * from table(dbms_xplan.display);
Plan hash value: 4238863598
--------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
--------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 25000 | 463K| 103 (1)| 00:00:01 |
|* 1 | TABLE ACCESS FULL| REALESTATE | 25000 | 463K| 103 (1)| 00:00:01 |
--------------------------------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
1 - filter("TYPE"='House')