今天是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>

innodbbufferpool은 데이터와 인덱싱 페이지를 캐싱하여 디스크 I/O를 줄여 데이터베이스 성능을 향상시킵니다. 작업 원칙에는 다음이 포함됩니다. 1. 데이터 읽기 : BufferPool의 데이터 읽기; 2. 데이터 작성 : 데이터 수정 후 BufferPool에 쓰고 정기적으로 디스크로 새로 고치십시오. 3. 캐시 관리 : LRU 알고리즘을 사용하여 캐시 페이지를 관리합니다. 4. 읽기 메커니즘 : 인접한 데이터 페이지를 미리로드합니다. Bufferpool을 크기를 조정하고 여러 인스턴스를 사용하여 데이터베이스 성능을 최적화 할 수 있습니다.

다른 프로그래밍 언어와 비교할 때 MySQL은 주로 데이터를 저장하고 관리하는 데 사용되는 반면 Python, Java 및 C와 같은 다른 언어는 논리적 처리 및 응용 프로그램 개발에 사용됩니다. MySQL은 데이터 관리 요구에 적합한 고성능, 확장 성 및 크로스 플랫폼 지원으로 유명하며 다른 언어는 데이터 분석, 엔터프라이즈 애플리케이션 및 시스템 프로그래밍과 같은 해당 분야에서 이점이 있습니다.

MySQL은 데이터 저장, 관리 및 분석에 적합한 강력한 오픈 소스 데이터베이스 관리 시스템이기 때문에 학습 할 가치가 있습니다. 1) MySQL은 SQL을 사용하여 데이터를 작동하고 구조화 된 데이터 관리에 적합한 관계형 데이터베이스입니다. 2) SQL 언어는 MySQL과 상호 작용하는 열쇠이며 CRUD 작업을 지원합니다. 3) MySQL의 작동 원리에는 클라이언트/서버 아키텍처, 스토리지 엔진 및 쿼리 최적화가 포함됩니다. 4) 기본 사용에는 데이터베이스 및 테이블 작성이 포함되며 고급 사용량은 Join을 사용하여 테이블을 결합하는 것과 관련이 있습니다. 5) 일반적인 오류에는 구문 오류 및 권한 문제가 포함되며 디버깅 기술에는 구문 확인 및 설명 명령 사용이 포함됩니다. 6) 성능 최적화에는 인덱스 사용, SQL 문의 최적화 및 데이터베이스의 정기 유지 보수가 포함됩니다.

MySQL은 초보자가 데이터베이스 기술을 배우는 데 적합합니다. 1. MySQL 서버 및 클라이언트 도구를 설치하십시오. 2. SELECT와 같은 기본 SQL 쿼리를 이해하십시오. 3. 마스터 데이터 작업 : 데이터를 만들고, 삽입, 업데이트 및 삭제합니다. 4. 고급 기술 배우기 : 하위 쿼리 및 창 함수. 5. 디버깅 및 최적화 : 구문 확인, 인덱스 사용, 선택*을 피하고 제한을 사용하십시오.

MySQL은 테이블 구조 및 SQL 쿼리를 통해 구조화 된 데이터를 효율적으로 관리하고 외래 키를 통해 테이블 간 관계를 구현합니다. 1. 테이블을 만들 때 데이터 형식을 정의하고 입력하십시오. 2. 외래 키를 사용하여 테이블 간의 관계를 설정하십시오. 3. 인덱싱 및 쿼리 최적화를 통해 성능을 향상시킵니다. 4. 데이터 보안 및 성능 최적화를 보장하기 위해 데이터베이스를 정기적으로 백업 및 모니터링합니다.

MySQL은 웹 개발에 널리 사용되는 오픈 소스 관계형 데이터베이스 관리 시스템입니다. 주요 기능에는 다음이 포함됩니다. 1. 다른 시나리오에 적합한 InnoDB 및 MyISAM과 같은 여러 스토리지 엔진을 지원합니다. 2.로드 밸런싱 및 데이터 백업을 용이하게하기 위해 마스터 슬레이브 복제 기능을 제공합니다. 3. 쿼리 최적화 및 색인 사용을 통해 쿼리 효율성을 향상시킵니다.

SQL은 MySQL 데이터베이스와 상호 작용하여 데이터 첨가, 삭제, 수정, 검사 및 데이터베이스 설계를 실현하는 데 사용됩니다. 1) SQL은 Select, Insert, Update, Delete 문을 통해 데이터 작업을 수행합니다. 2) 데이터베이스 설계 및 관리에 대한 생성, 변경, 삭제 문을 사용하십시오. 3) 복잡한 쿼리 및 데이터 분석은 SQL을 통해 구현되어 비즈니스 의사 결정 효율성을 향상시킵니다.

MySQL의 기본 작업에는 데이터베이스, 테이블 작성 및 SQL을 사용하여 데이터에서 CRUD 작업을 수행하는 것이 포함됩니다. 1. 데이터베이스 생성 : createAbasemy_first_db; 2. 테이블 만들기 : CreateTableBooks (idintauto_incrementprimarykey, titlevarchar (100) notnull, authorvarchar (100) notnull, published_yearint); 3. 데이터 삽입 : InsertIntobooks (Title, Author, Published_year) VA


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경
