首页 > 代码库 > SQL笔记-第六章,索引与约束
SQL笔记-第六章,索引与约束
一.索引
CREATE INDEX 索引名 ON 表名(字段1, 字段2,……字段n)
CREATE INDEX idx_person_nameage ON T_Person(FName,FAge)
DROP INDEX 索引名ON 表名
DROP INDEX idx_person_nameage ON T_Person;
二.约束
数据库系统中主要提供了如下几种约束:
非空约束;唯一约束; CHECK 约束;主键约束;外键约束
1.非空约束
CREATE TABLE T_Person
(FNumber VARCHAR(20) NOT NULL ,
FName VARCHAR(20),
FAge INT)
2.唯一约束
CREATE TABLE T_Person (FNumber VARCHAR(20) UNIQUE, FName VARCHAR(20),FAge INT)
复合唯一约束
CONSTRAINT 约束名UNIQUE(字段1,字段2……字段n)
CREATE TABLE T_Person (FNumber VARCHAR(20),
FDepartmentNumber VARCHAR(20),
FName VARCHAR(20),FAge INT,
CONSTRAINT unic_1 UNIQUE(FNumber,FDepartmentNumber) ,
CONSTRAINT unic_2 UNIQUE(FDepartmentNumber, FName))
ALTER TABLE T_Person DROP CONSTRAINT unic_1;
ALTER TABLE T_Person DROP CONSTRAINT unic_2;
ALTER TABLE T_Person DROP CONSTRAINT unic_3;
3.CHECK约束
CREATE TABLE T_Person (
FNumber VARCHAR(20),
FName VARCHAR(20),
FAge INT CHECK(FAge >0),
FWorkYear INT CHECK(FWorkYear>0))
ALTER TABLE T_Person
ADD CONSTRAINT ck_2 CHECK(FAge>14)
4.主键约束
在字段定义后添加 PRIMARY KEY 关键字即可
追加
ALTER TABLE T_Person
ADD CONSTRAINT pk_1 PRIMARY KEY(FNumber,FName)
外键约束
CREATE TABLE T_AUTHOR
(
FId VARCHAR(20) PRIMARY KEY,
FName VARCHAR(100),
FAge INT,
FEmail VARCHAR(20)
);
CREATE TABLE T_Book
(
FId VARCHAR(20) PRIMARY KEY,
FName VARCHAR(100),
FPageCount INT,
FAuthorId VARCHAR(20) ,
FOREIGN KEY (FAuthorId) REFERENCES T_AUTHOR(FId)
);
删除
DELETE FROM T_Book WHERE FAuthorId =5;
DELETE FROM T_AUTHOR WHERE FName=’badboy’
追加
ALTER TABLE T_Book
ADD CONSTRAINT fk_book_author
FOREIGN KEY (FAuthorId) REFERENCES T_AUTHOR(FId)
SQL笔记-第六章,索引与约束