MySQL_约束条件

扫码查看

八个约束条件

1.非空约束NOT NULL

  • 非空约束___创建表时添加约束
create table 表名
(
    a int not null,
    b int not null,
);
  • 非空约束___修改表时添加约束
alter table 表名
modify 字段名 类型 not null;
  • 非空约束___删除约束
alter table 表名
modify 字段名 类型;

2.主键约束PRIMARY KEY

  • 主键约束___创建表时添加约束.
create table 表名
(
    a int,
    b int,
    c int,
    primary key(字段1,字段2)
);
create table 表名
(
    a int,
    b int,
    c int,
    constraint 约束名 primary key(字段1,...)
);
create table 表名
(
    a int primary key,
    b int,
    c int
);
  • 主键约束___修改表时添加约束
alter tbale 表名
modify 字段名 类型 primary key;
alter table 表名
primary key(字段1,字段2);
alter table 表名
add constraint 约束名 primary key(字段1,字段2);
  • 主键约束___删除约束
alter table 表名
drop primary key;

3.多字段联合主键(复合主键)

  • 多字段联合约束___创建多字段联合主键
create table 表名
(
    a int,
    b int,
    primary key(字段1,字段2)
);

4.唯一约束UNIQUE

  • 唯一约束___创建表时添加约束
create table 表名
(
    a int unqiue,
    b int,
    c int
);
create table 表名
(
    a int,
    b int,
    c int,
    constraint usfz unique(字段名,...)
);
create table 表名
(
    a int,
    b int,
    c int,
    unique(字段名,...)
);
  • 唯一约束___修改表时添加约束
alter tbale 表名
modify 字段名 类型 unique;
alter table 表名
add unique(字段1,字段2);
alter table 表名
add constraint 约束名 unique(字段1,字段2);
  • 唯一约束___删除约束
alter table 表名
drop index 约束名;
alter table 表名
drop key 约束名称;

5.默认约束DEFAULT

  • 默认约束___创建表时添加约束
create table 表名
(
    a int primary key,
    b int default '123456'
);
  • 默认约束___修改表时添加约束
alter table 表名
modify 字段名 类型 default '1234';
alter table 表名
alter column 字段名 set default '1234';
  • 默认约束___删除约束
alter table 表名
modify 字段名 类型;
alter table 表名
alter column 字段 drop default;

6.外键约束FOREIGN KEY

  • 外键约束___创建表时添加约束
create table 从表名
(
    a int,
    b int,
    constraint 外键约束名 foreign key (从表字段名)
    references 主表名 (主表主键)
);
  • 外键约束___修改表时添加约束
alter table 从表名
add foreign key(从表字段名)
references 主表名(主表字段);
  • 外键约束___删除约束
alter table 从表名
drop foreign key 从表字段名;
  • 从父表删除或更新且自动删除或更新子表中匹配的行
create able 从表名
(
    a int,
    b int,
    consteraint fk_cid
    foreign key(从表字段名)
    references 主表表名(主表字段名) on delete cascade
);

7.自增约束 auto_increment

https://www.cnblogs.com/iforever/p/10071733.html

  • 自增列___创建表时添加约束

create tbale 表名
(
    a int primary key auto_increment,
    b int
);
create table 表名
(
    a int primary key auto_increment,
    b int
)auto_increment=9;
  • 自增列___修改表时添加约束
alter table 表名
modify 字段名 字段类型 auto_increment;
alter table 表名
auto_increment=9;
  • 自增列___删除约束
alter table 表名
modify 字段名 字段类型;
  • 检查约束___创建表时添加约束
create table 表名
(
   a int,
   b int check(字段名>0 and 字段名<100)
);
create table 表名
(
   a int,
   check(字段名>100)
);
  • 检查约束___修改表时添加约束
alter table 表名
add constraint 约束名 check(字段名>100);
  • 检查约束___删除约束
alter table 表名
drop constraint 检查约束名;
12-23 07:41
查看更多