1.约束
非空约束 | not null |
唯一约束 | unique |
主键约束 | primary key |
检查约束 | check |
默认约束 | default |
外键约束 | foreign key |
1.1非空约束
添加
-- 创建表时添加非空约束
create table 表名(
列名 数据类型 not null,
…
);
-- 建完表后添加非空约束
alter table 表名 modify 字段名 数据类型 not null;
删除
alter table 表名 modify 字段名 数据类型;
1.2唯一约束
添加
-- 创建表时添加唯一约束
create table 表名(
列名 数据类型 unique [auto_increment],
-- auto_increment: 当不指定值时自动增长
…
);
create table 表名(
列名 数据类型,
…
[constraint] [约束名称] unique (列名)
);
-- 建完表后添加唯一约束
alter table 表名 modify 字段名 数据类型 UNIQUE;
删除
alter table 表名 drop index字段名;
1.3主键约束
添加
-- 创建表时添加主键约束
create table 表名(
列名 数据类型 primary key [auto_increment],
…
);
create table 表名(
列名 数据类型,
[constraint] [约束名称] primary key(列名)
);
-- 建完表后添加主键约束
alter table 表名 add primary key(字段名);
删除
alter table 表名 drop primary key;
1.4默认约束
添加
-- 创建表时添加默认约束
create table 表名(
列名 数据类型 default 默认值,
…
);
-- 建完表后添加默认约束
alter table 表名 alter 列名 set default 默认值;
删除
alter table 表名 alter 列名 drop default;
1.5外键约束
添加
-- 创建表时添加外键约束
create table 表名(
列名 数据类型,
…
[constraint] [外键名称] foreign key (外键列名) references 主表(主表列名)
);
-- 建完表后添加外键约束
alter table 表名 add constraint 外键名称 foreign key (外键字段名称) references 主表名称(主表列名称);
删除
alter table 表名 drop forengin key 外键名称;
2.数据库设计
软件的研发步骤