mysql_约束条件

1.not null和default

# sex字段不可为空,默认值为''
create table t2(
    id int,
    name char(10),
    sex enum('','') not null default ''
);

2.unique key

  单列唯一:

# id和name字段中的值不可重复
# 方式一
create table t4(
    id int unique key,
    name char(10) unique key
);
# 方式二
create table t5(
  id int,
  name char(10),
  unique(id),
  unique(name) );

  联合唯一:

# id和name不能同时重复
create table t5(
  id int,
  name char(10),
  unique(id,name)
);

3.primary key(主键)

  对于innodb存储引擎来说,一张表必须有一个主键。

  单列主键

# 创建表t1,将id字段设为主键,id字段不为空切唯一。
create table t1(
    id int primary key,
    name char(10)
);

  复合主键

# 将字段ip和字段port联合在一起成为复合主键,这两个字段不能为空,且不能同时重复。
create table t2(
    ip char(15),
    port int,
    primary key(ip,port)
);

4.auto_increment(自增长,但是设置自增长的字段必须是key)

# 创建表t3,将t3表中的id字段(主键)设为自增长。
create table t3(
    id int primary key auto_increment,
    name char(10)
);

  有自增长的表清空表时,用delete清空表后,再往表中插入数据,自增字段是接着清空之前的。

  用“truncate 表名”清空表后,自增字段重新变为1。应该用teuncate来清空表

5.foreign key(外键)

# 将t2_id字段设置为外键,并关联t2表中的id字段(前提是t2表已经存在,并有id字段,且表t2中id字段是唯一的)
create table t1(
    id int primary key,
    name char(10),
    t2_id int,
    foreign key(t2_id) references t2(id)
);

  注意:

    插入记录时,先往被关联表中插入记录,才可以往关联表中的外键插入被关联表中的已经存中的记录。

    删除记录时,需要先删除关联表中的记录,才可以删除被关联表中的记录。或者创建关联表时,将外键后面加 on delete cascade(删除同步)

reate table t1(
    id int primary key,
    name char(10),
    t2_id int,
    foreign key(t2_id) references t2(id) on delete cascade
);

    更新同步:on update cascade

reate table t1(
    id int primary key,
    name char(10),
    t2_id int,
    foreign key(t2_id) references t2(id) on delete cascade on update cascade
);

  设置同步后,只需要操作被关联表中的记录,关联表中的记录也会发送改变。

posted @ 2020-01-16 23:19  手可摘星辰。  阅读(146)  评论(0编辑  收藏  举报