索引和约束
1、索引
create table t_person(FNumber varchar(20),FName varchar(20),FAge int);
创建索引的语法:
create index 索引名 on 表名(字段1,字段2,.....字段n)
create index idx_person_name on t_person(FNumber)
create index idx_person_nameage on t_person(FName,FAge)
删除索引语法:
drop index idx_person_name on t_person;
drop idx_person_nameage on t_person;
2、约束
2.1非空约束 not null
create table t_person(FNumber varchar(20) not null, FName varchar(20),FAge int)
2.2唯一约束 unique
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_dep_num unique(FNumber,FDepartmentNumber))
创建多个复合唯一约束
create table t_person(FNumber varchar(20),FDepartmentNumber varchar(20), FName varchar(20), FAge int, constraint unic1 unique(FNumber,FDepartmentNumber),constraint unic2 unique(FDepartmentNumber,FName))
2.2check约束 用来检查记录中的值是否满足一个条件
create table t_person(FNumber varchar(20), FName varchar(20),FAge int check(FAge>0),FWorkYear int check(FWorkYear>0));
check约束也可以使用函数进行操作
create table t_person(FNumber varchar(20) check(length(FNumber)>12), FName varchar(20),FAge int check(FAge>0),FWorkYear int check(FWorkYear>0));
check字句中引用其他的列语法如下:
constraint 约束名 check(约束条件)
create table t_person(FNumber varchar(20),FName varchar(20),FAge int,FWorkYear int, constraint ck_1 check(FWorkYear<FAge));
2.3主键约束
create table t_person(FNumber varchar(20) primary key, FName varchar(20),FAge int)
多字段组成的主键约束
create table t_person(FNumber varchar(20), FName varchar(20),FAge int constraint pk_1 primary key(FNumber,FName))
2.4外键约束
create table t_author(FId varchar(20) primary key,FName varchar(20),FAge int,FE-mail 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(id));
create table t_person(FNumber varchar(20), FName varchar(20),FAge int constraint pk_1 primary key(FNumber,FName))
2.4外键约束