Home Database Mysql Tutorial 关于复合主键查询时使用索引研究

关于复合主键查询时使用索引研究

Jun 07, 2016 pm 05:40 PM
sql sql optimization database index

当数据库创建表时,每个表只能有一个主键,但是如果想让多个列都成为主键时,就要用到复合主键。一、主键唯一约束我们知道当某列为主键时,Oracle会自动将此列创

当数据库创建表时,每个表只能有一个主键,但是如果想让多个列都成为主键时,就要用到复合主键。

一、主键唯一约束

我们知道当某列为主键时,Oracle会自动将此列创建唯一约束。也就是说不允许有相同的值出现。

如:

CREATE TABLE T

(

ID NUMBER,

NAME VARCHAR2(10),

constraint t_pk primary key (ID)

);  

table T 已创建。

INSERT INTO T VALUES(1,'A');

1 行已插入。

insert into T VALUES(1,'B');

SQL 错误: ORA-00001: 违反唯一约束条件 (TEST.T_PK)

 

复合主键创建的约束指的是不允许三个值都重复的数据插入

如:

CREATE TABLE T

(

ID1 NUMBER,

ID2 NUMBER,

ID3 NUMBER,

NAME VARCHAR2(10),

constraint t_pk primary key (ID1,ID2,ID3)

);

table T 已创建。

INSERT INTO T VALUES(1,1,1,'A');

1 行已插入。

INSERT INTO T VALUES(1,1,2,'B');

1 行已插入。

INSERT INTO T VALUES(1,2,1,'A');

1 行已插入。

INSERT INTO T VALUES(1,1,2,'B');

SQL 错误: ORA-00001: 违反唯一约束条件 (TEST.T_PK)

 二、主键索引

当创建主键时Oracle会自动创建索引。

如:

CREATE TABLE T1

(

ID NUMBER,

NAME VARCHAR2(10),

CONSTRAINT T1_PK PRIMARY KEY (ID)

);

...插入部分数据...

SELECT * FROM T1 WHERE id = 10;

查看Oracle的解释计划

很明显Oracle使用了索引来查询。

而当执行一下查询时由于没有索引列,所以使用的是全表扫描查询。

SELECT * FROM T1 where name = 'A';

SELECT * FROM T1 ;

当创建复合索引时包含全部索引列时Oracle会以索引方式进行查询。

SELECT * FROM T WHERE ID1 = 2 AND ID2 = 3 AND ID3 = 1;

当条件包含部分索引列时会发生两种情况。我们重新创建一张表REPOLICYSHARE,向表内插入500000行数据。

CREATE TABLE REPOLICYSHARE

    (

        POLICYNO   VARCHAR2(22),

        DANGERNO   NUMBER(8,0),

        REPOLICYNO VARCHAR2(22) NOT NULL,

        STARTDATE DATE,

        CLASSCODE     VARCHAR2(4),

        RISKCODE      VARCHAR2(4),

        COMCODE       VARCHAR2(10) NOT NULL,

        REINSMODE     VARCHAR2(3) NOT NULL,

        TREATYNO      VARCHAR2(10) NOT NULL,

        TREATYSECTION VARCHAR2(12),

        SHARERATE     NUMBER(9,6),

        CURRENCY      VARCHAR2(3),

        REAMOUNT      NUMBER(14,2),

        REPREMIUM     NUMBER(14,2),

        EXCHRATECNY   NUMBER(12,8),

        ACCPAYDATE DATE NOT NULL,

        TREATYFLAG VARCHAR2(1) NOT NULL,

        PAYDATE DATE NOT NULL,

        STATDATE DATE,

        CONSTRAINT PK_MID_R_REPOLICYSHARE PRIMARY KEY (REPOLICYNO,

        COMCODE, TREATYNO, ACCPAYDATE, PAYDATE, TREATYFLAG,

        CURRENCY)

        );

由建表语句我们能看出此表的所因为复合索引,并且由REPOLICYNO, COMCODE, TREATYNO, ACCPAYDATE, PAYDATE, TREATYFLAG, CURRENCY等列构成。

当where条件包含REPOLICYNO, COMCODE, TREATYNO列时。使用的是索引查询。

SELECT POLICYNO

FROM REPOLICYSHARE

WHERE REPOLICYNO = 'PO0520062458001329'

AND COMCODE      = '2458800605'

AND TREATYNO     = 'OP2006ZL';

当where条件包含COMCODE, TREATYNO列时。使用的是全表扫描查询。

SELECT POLICYNO

FROM REPOLICYSHARE

WHERE COMCODE      = '2458800605'

AND TREATYNO     = 'OP2006ZL';

为什么同样是部分列,但查询形式却不一样呢?

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

How to use database callback functions in Golang? How to use database callback functions in Golang? Jun 03, 2024 pm 02:20 PM

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

PHP Database Connection Pitfalls: Avoid Common Mistakes and Misunderstandings PHP Database Connection Pitfalls: Avoid Common Mistakes and Misunderstandings Jun 05, 2024 pm 10:21 PM

To avoid PHP database connection errors, follow best practices: check for connection errors and match variable names with credentials. Use secure storage or environment variables to avoid hardcoding credentials. Close the connection after use to prevent SQL injection and use prepared statements or bound parameters.

How does Go WebSocket integrate with databases? How does Go WebSocket integrate with databases? Jun 05, 2024 pm 03:18 PM

How to integrate GoWebSocket with a database: Set up a database connection: Use the database/sql package to connect to the database. Store WebSocket messages to the database: Use the INSERT statement to insert the message into the database. Retrieve WebSocket messages from the database: Use the SELECT statement to retrieve messages from the database.

See all articles