六项约束

非空约束

create table 表名(

  id int not null

  );

  

唯一约束

create table 表名(

  id int unique key,

  name varchar(20)

  );

主键约束 primary key

主键的作用:可以唯一标示一条数据,每张表里只有一个主键。

主键的特性:非空唯一。当表里没有主键时,第一个出现的非空且唯一的列,被当成主键。

creat table 表名(

  id int primary key,

  name varchar(20)

  );

删除主键约束:

alter table 表名

  drop primary key;

自增长 auto_increment 

自动编号,一般与主键组合使用。一个表里面只能有一个自增长,默认情况下起始值为1,每次增量为1。

create table 表名(

  id int primary key auto_increment,

  name varchar(20)

  )auto_increment = 100;  # 不加auto_increment=100,起始值是1。

默认约束 default

初始值设置,插入记录时,如果没有

create table 表名(

  id int primary key auto_increment,

  name varchar(20) not null,

  age int not null default 18

  );

外键约束 foreign key

保持数据的一致性,完整性实现一对多关系。外键必须关联到键上面去,一般情况是关联到另一张表的主键

foreign key (本列表的字段名) reference 其他表名(要关联的字段名)

原文地址:https://www.cnblogs.com/mxwei/p/9142592.html