搜索
首页数据库mysql教程复合索引和INDEXSKIPSCAN

今天是2014-01-21,在此学习一下复合索引和INDEX SKIP SCAN; 复合索引很简单无非就是在创建索引的时候指定接字段,但是要注意字段的选择是有一定的可参考性的,在字段选择的时候我们一般将where条件之后经常使用的字段创建为复合索引,也就是说where条件自居

今天是2014-01-21,在此学习一下复合索引和INDEX SKIP SCAN;

复合索引很简单无非就是在创建索引的时候指定接字段,但是要注意字段的选择是有一定的可参考性的,在字段选择的时候我们一般将where条件之后经常使用的字段创建为复合索引,也就是说where条件自居中不同的键一起频繁出现,且使用“与”操作这些列时复合索引是不错的选择。

eg:

SQL> select index_type,index_name,table_name from user_indexes where table_name=upper('dept');

INDEX_TYPE                  INDEX_NAME                     TABLE_NAME
--------------------------- ------------------------------ ------------------------------
NORMAL                      DEPT_PK                        DEPT

SQL> drop index dept_pk;
drop index dept_pk
           *
ERROR at line 1:
ORA-02429: cannot drop index used for enforcement of unique/primary key

SQL> alter table dept drop constraint dept_pk;
alter table dept drop constraint dept_pk
                                 *
ERROR at line 1:
ORA-02273: this unique/primary key is referenced by some foreign keys

SQL>  select constraint_name,constraint_type,table_name,status from user_constraints where table_name in ('DEPT','EMP');

CONSTRAINT_NAME                C TABLE_NAME                     STATUS
------------------------------ - ------------------------------ --------
DEPT_PK                        P DEPT                           ENABLED
EMP_FK                         R EMP                            ENABLED

SQL> ALTER TABLE EMP DROP CONSTRAINT EMP_FK;

Table altered.

SQL> ALTER TABLE DEPT DROP CONSTRAINT DEPT_PK;

Table altered.

SQL> 

创建复合索引:

SQL>  create index dept_idx1 on dept(deptno,dname);

Index created.

SQL> set autotrace trace exp
SQL> select * from dept where deptno=20;

Execution Plan
----------------------------------------------------------
Plan hash value: 2855125856

-----------------------------------------------------------------------------------------
| Id  | Operation                   | Name      | Rows  | Bytes | Cost (%CPU)| Time     |
-----------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT            |           |     1 |    18 |     2   (0)| 00:00:01 |
|   1 |  TABLE ACCESS BY INDEX ROWID| DEPT      |     1 |    18 |     2   (0)| 00:00:01 |
|*  2 |   INDEX RANGE SCAN          | DEPT_IDX1 |     1 |       |     1   (0)| 00:00:01 |
-----------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   2 - access("DEPTNO"=20)

SQL> 

可以看到在只查询前导列deptno的时候,出现了索引范围扫描,但是由于loc字段没有在复合索引列中,那么还需要增加对表的扫描,无疑增加了额外的I/0,。

重新选择复合索引列值:

eg:

SQL> set autotrace off
SQL> drop index dept_idx1;

Index dropped.

SQL> create index dept_idx1 on dept(deptno,dname,loc);

Index created.

SQL> set autotrace trace exp
SQL> select * from dept where deptno=20;

Execution Plan
----------------------------------------------------------
Plan hash value: 2571496166

------------------------------------------------------------------------------
| Id  | Operation        | Name      | Rows  | Bytes | Cost (%CPU)| Time     |
------------------------------------------------------------------------------
|   0 | SELECT STATEMENT |           |     1 |    18 |     1   (0)| 00:00:01 |
|*  1 |  INDEX RANGE SCAN| DEPT_IDX1 |     1 |    18 |     1   (0)| 00:00:01 |
------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - access("DEPTNO"=20)

SQL> 


可以看到在选择复合索引的列值是应该注意的地方。在此只是一个非常简单的例子,但是却反应了一个很大问题所在。

对于 index skip scan是从oracle 9I引入的,当没引入该技术时,在复合索引中,如果where条件没有使用到前导列,那么就走全表扫描而不使用索引,在9I之后该技术的引入才打破了这一局限。

官方介绍:

Index skip scans improve index scans by non-prefix columns since it is often faster to scan index blocks than scanning table data blocks. A non-prefix index is an index which does not contain a key column as its first column.

This concept is easier to understand if one imagines a prefix index to be similar to a partitioned table. In a partitioned object the partition key (in this case the leading column) defines which partition data is stored within. In the index case every row underneath each key (the prefix column) would be ordered under that key. Thus in a skip scan of a prefixed index, the prefixed value is skipped and the non-prefix columns are accessed as logical sub-indexes. The trailing columns are ordered within the prefix column and so a 'normal' index access can be done ignoring the prefix.

In this case a composite index is split logically into smaller subindexes. The number of logical subindexes depends on the cardinality of the initial column. Hence it is now possible to use the index even if the leading column is not used in a where clause.

也就是说,索引跳跃式扫描及时通过逻辑子索引消除或跳过一个复合索引,这个时候复合索引可以认为化成了几个逻辑子索引。如果在where条件中没有使用前导列就会采用索引跳跃式扫描。

在看如下例子:

SQL> select dbms_metadata.get_ddl('INDEX','EMP_IDX1','AMY') FROM DUAL; DBMS_METADATA.GET_DDL('INDEX','EMP_IDX1','AMY') -------------------------------------------------------------------------------- CREATE INDEX "AMY"."EMP_IDX1" ON "AMY"."EMP" ("EMPNO", "ENAME", "SAL") PCT SQL> SQL> set autotrace trace exp SQL> SQL> select * from emp where sal=1250; Execution Plan ---------------------------------------------------------- Plan hash value: 954130750 ---------------------------------------------------------------------------------------- | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time | ---------------------------------------------------------------------------------------- | 0 | SELECT STATEMENT | | 1 | 32 | 2 (0)| 00:00:01 | | 1 | TABLE ACCESS BY INDEX ROWID| EMP | 1 | 32 | 2 (0)| 00:00:01 | |* 2 | INDEX SKIP SCAN | EMP_IDX1 | 1 | | 1 (0)| 00:00:01 | ---------------------------------------------------------------------------------------- Predicate Information (identified by operation id): --------------------------------------------------- 2 - access("SAL"=1250) filter("SAL"=1250) SQL> [oracle@oracle-one ~]$ sqlplus / as sysdba SQL*Plus: Release 11.2.0.4.0 Production on Tue Jan 21 15:24:25 2014 Copyright (c) 1982, 2013, Oracle. All rights reserved. Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production With the Partitioning, Automatic Storage Management, OLAP, Data Mining and Real Application Testing options SQL> conn amy/rhys Connected. SQL> alter session set events '10046 trace name context forever,level 12'; Session altered. SQL> select * from emp where sal=1250; EMPNO ENAME JOB MGR HIREDATE SAL COMM ---------- ---------- --------- ---------- --------- ---------- ---------- DEPTNO ---------- 7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30 7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30 SQL> alter session set events '10046 trace name context off'; Session altered. SQL> SQL> select * from v$diag_info; INST_ID NAME VALUE ---------- ------------------------------------------------------------ ------------------------------------------------------------ 1 Diag Enabled TRUE 1 ADR Base /opt/app/oracle 1 ADR Home /opt/app/oracle/diag/rdbms/rhys/RHYS 1 Diag Trace /opt/app/oracle/diag/rdbms/rhys/RHYS/trace 1 Diag Alert /opt/app/oracle/diag/rdbms/rhys/RHYS/alert 1 Diag Incident /opt/app/oracle/diag/rdbms/rhys/RHYS/incident 1 Diag Cdump /opt/app/oracle/diag/rdbms/rhys/RHYS/cdump 1 Health Monitor /opt/app/oracle/diag/rdbms/rhys/RHYS/hm 1 Default Trace File /opt/app/oracle/diag/rdbms/rhys/RHYS/trace/RHYS_ora_4694.trc 1 Active Problem Count 1 1 Active Incident Count 1 11 rows selected. SQL> 看一下执行计划: [oracle@oracle-one script]$ tkprof RHYS_ora_4694.trc tkprof_4694.txt sys=no aggregate=yes explain=amy/rhys record=record_sql.sql waits=yes TKPROF: Release 11.2.0.4.0 - Development on Tue Jan 21 15:31:42 2014 Copyright (c) 1982, 2011, Oracle and/or its affiliates. All rights reserved. [oracle@oracle-one script]$ [oracle@oracle-one script]$ vi tkprof_4694.txt TKPROF: Release 11.2.0.4.0 - Development on Tue Jan 21 15:31:42 2014 Copyright (c) 1982, 2011, Oracle and/or its affiliates. All rights reserved. Trace file: RHYS_ora_4694.trc Sort options: default ******************************************************************************** count = number of times OCI procedure was executed cpu = cpu time in seconds executing elapsed = elapsed time in seconds executing disk = number of physical reads of buffers from disk query = number of buffers gotten for consistent read current = number of buffers gotten in current mode (usually for update) rows = number of rows processed by the fetch or execute call ******************************************************************************** SQL ID: ajqsk3f0nk06d Plan Hash: 954130750 select * from emp where sal=1250 call count cpu elapsed disk query current rows ------- ------ -------- ---------- ---------- ---------- ---------- ---------- Parse 1 0.00 0.03 0 0 0 0 Execute 1 0.00 0.00 0 0 0 0 Fetch 2 0.00 0.00 0 4 0 2 ------- ------ -------- ---------- ---------- ---------- ---------- ---------- total 4 0.00 0.03 0 4 0 2 Misses in library cache during parse: 1 Optimizer mode: ALL_ROWS Parsing user id: 90 (AMY) Number of plan statistics captured: 1 Rows (1st) Rows (avg) Rows (max) Row Source Operation ---------- ---------- ---------- --------------------------------------------------- 2 2 2 TABLE ACCESS BY INDEX ROWID EMP (cr=4 pr=0 pw=0 time=41 us cost=2 size=32 card=1) 2 2 2 INDEX SKIP SCAN EMP_IDX1 (cr=2 pr=0 pw=0 time=42 us cost=1 size=0 card=1)(object id 88000) Rows Execution Plan ------- --------------------------------------------------- 0 SELECT STATEMENT MODE: ALL_ROWS 2 TABLE ACCESS MODE: ANALYZED (BY INDEX ROWID) OF 'EMP' (TABLE) 2 INDEX MODE: ANALYZED (SKIP SCAN) OF 'EMP_IDX1' (INDEX) Elapsed times include waiting on following events: Event waited on Times Max. Wait Total Waited ---------------------------------------- Waited ---------- ------------ SQL*Net message to client 2 0.00 0.00 SQL*Net message from client 2 14.93 14.93 ******************************************************************************** SQL>
声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
解释InnoDB缓冲池及其对性能的重要性。解释InnoDB缓冲池及其对性能的重要性。Apr 19, 2025 am 12:24 AM

InnoDBBufferPool通过缓存数据和索引页来减少磁盘I/O,提升数据库性能。其工作原理包括:1.数据读取:从BufferPool中读取数据;2.数据写入:修改数据后写入BufferPool并定期刷新到磁盘;3.缓存管理:使用LRU算法管理缓存页;4.预读机制:提前加载相邻数据页。通过调整BufferPool大小和使用多个实例,可以优化数据库性能。

MySQL与其他编程语言:一种比较MySQL与其他编程语言:一种比较Apr 19, 2025 am 12:22 AM

MySQL与其他编程语言相比,主要用于存储和管理数据,而其他语言如Python、Java、C 则用于逻辑处理和应用开发。 MySQL以其高性能、可扩展性和跨平台支持着称,适合数据管理需求,而其他语言在各自领域如数据分析、企业应用和系统编程中各有优势。

学习MySQL:新用户的分步指南学习MySQL:新用户的分步指南Apr 19, 2025 am 12:19 AM

MySQL值得学习,因为它是强大的开源数据库管理系统,适用于数据存储、管理和分析。1)MySQL是关系型数据库,使用SQL操作数据,适合结构化数据管理。2)SQL语言是与MySQL交互的关键,支持CRUD操作。3)MySQL的工作原理包括客户端/服务器架构、存储引擎和查询优化器。4)基本用法包括创建数据库和表,高级用法涉及使用JOIN连接表。5)常见错误包括语法错误和权限问题,调试技巧包括检查语法和使用EXPLAIN命令。6)性能优化涉及使用索引、优化SQL语句和定期维护数据库。

MySQL:初学者的基本技能MySQL:初学者的基本技能Apr 18, 2025 am 12:24 AM

MySQL适合初学者学习数据库技能。1.安装MySQL服务器和客户端工具。2.理解基本SQL查询,如SELECT。3.掌握数据操作:创建表、插入、更新、删除数据。4.学习高级技巧:子查询和窗口函数。5.调试和优化:检查语法、使用索引、避免SELECT*,并使用LIMIT。

MySQL:结构化数据和关系数据库MySQL:结构化数据和关系数据库Apr 18, 2025 am 12:22 AM

MySQL通过表结构和SQL查询高效管理结构化数据,并通过外键实现表间关系。1.创建表时定义数据格式和类型。2.使用外键建立表间关系。3.通过索引和查询优化提高性能。4.定期备份和监控数据库确保数据安全和性能优化。

MySQL:解释的关键功能和功能MySQL:解释的关键功能和功能Apr 18, 2025 am 12:17 AM

MySQL是一个开源的关系型数据库管理系统,广泛应用于Web开发。它的关键特性包括:1.支持多种存储引擎,如InnoDB和MyISAM,适用于不同场景;2.提供主从复制功能,利于负载均衡和数据备份;3.通过查询优化和索引使用提高查询效率。

SQL的目的:与MySQL数据库进行交互SQL的目的:与MySQL数据库进行交互Apr 18, 2025 am 12:12 AM

SQL用于与MySQL数据库交互,实现数据的增、删、改、查及数据库设计。1)SQL通过SELECT、INSERT、UPDATE、DELETE语句进行数据操作;2)使用CREATE、ALTER、DROP语句进行数据库设计和管理;3)复杂查询和数据分析通过SQL实现,提升业务决策效率。

初学者的MySQL:开始数据库管理初学者的MySQL:开始数据库管理Apr 18, 2025 am 12:10 AM

MySQL的基本操作包括创建数据库、表格,及使用SQL进行数据的CRUD操作。1.创建数据库:CREATEDATABASEmy_first_db;2.创建表格:CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY,titleVARCHAR(100)NOTNULL,authorVARCHAR(100)NOTNULL,published_yearINT);3.插入数据:INSERTINTObooks(title,author,published_year)VA

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中