MySQL数据库从入门到精通 第五章内容总结
主键约束 / 唯一约束 / 自动增长列
主键约束 PRIMARY KEY
create table stu(
s_id int PRIMARY KEY,
s_name varchar(20),
sfz_id char(18),
phone char(11)[,]
[PRIMARY KEY(s_id,sfz_id)]
);
alter table stu add PRIMARY KEY(新字段);
唯一约束 UNIQUE
create table stu(
s_id int primary key,
s_name varchar(20),
sfz_id char(18) UNIQUE,
phone char(11)
);
alter table stu add UNIQUE(新字段);
自动增长列 AUTO_INCREMENT
create table stu(
s_id int primary key AUTO_INCREMENT,
s_name varchar(20),
sfz_id char(18),
phone char(11)
);
alter table stu MODIFY s_id int primary key AUTO_INCREMENT;
普通索引 / 唯一索引
普通索引
create table 表名称(
字段名 数据类型,
···
INDEX[ 索引名](字段名)[(长度)]
);
create table stu(
s_id int,
name varchar(20),
INDEX(name)
);
create INDEX 索引名 ON 表名称(字段名[(长度)]);
唯一索引
create table 表名称(
字段名 数据类型,
···
UNIQUE INDEX[ 索引名](字段名)[(长度)]
);
create table stu(
s_id int,
name varchar(20),
UNIQUE INDEX(name)
);
create UNIQUE INDEX 索引名 ON 表名称(字段名[(长度)]);
域完整性
非空约束 NOT NULL
create table 表名称(
字段名 数据类型 NOT NULL,
···
);
alter table 表名称 modify 字段名 数据类型 NOT NULL;
默认值约束 DEFAULT
create table 表名称(
字段名 数据类型 DEFAULT 默认值,
···
);
alter table 表名称 modify 字段名 数据类型 DAFAULT;
引用完整性(参照完整性)
添加外键约束
cerate table 表名称(
字段名 数据类型,
···,
FOREIGH KEY(外键字段名) REFERENCES 主表表名(主键字段名)
);
alter table 表名称 add FOREIGH KEY(外键字段名) REFERENCES 主表名(主键字段名);
删除外键约束
alter table 表名称 drop FOREIGH KEY 外键名;
外键名获取
show create table student\G;