sql语句之约束条件

 

not null约束,需设置默认值

sex enum('male','female') not null default 'male'

 

unique 约束,值唯一

单列唯一:

create table department(

  id int unique,

  name char(10) unique);

或者

create table department(

  id int,

  name char(10),

  unique(id),

  unique(name));

联合唯一:

create table department(

  id int,

  name char(10),

  unique(id,name));

 

primary key

满足 not null,unique

对innodb存储引擎来说,一张表内必须有一个主键,当不指定主键时,会默认选一列满足not null和unique的列做主键,如果没有,会设一个隐藏列做主键。

单列主键和复合主键。

primary key(id1,id2)

 

auto_increment

create table t20(

  id int primary key auto_increment,    #如果不指定id值,id会自动自增,如果指定则按指定的id值

  name char(16))

  AUTO_INCREMENT = 4;     # 设定id起始值为4

alter table set auto_increment = 1   # 修改起始值

补充:

  show variables like 'auto_inc%'  # 查询变量

  auto_increment_increment     # 步长,默认为1

  auto_increment_offset       # 起始偏移量,默认为1

  set session auto_increment_increment=5;  # 该步长基于会话级别,会话关闭,步长失效。而sql server可以给表设置步长  

  set global auto_increment_increment=5; # 设置所有会话,会话关闭后再开启,步长还是5

  清空表要用truncate,如truncate t20,能置自增的序列为初始状态,而delete不能,delete宜和where配合删除具体一行。

 

foreign key

先建被关联的表,并保证被关联的字段唯一。

再建关联表:

dept_id int,

foreign key(dept_id)  references dept(id) on delete cascade on update cascade   

或 CONSTRAINT fk_dept foreign key(dept_id) REFERENCE dept(id)

 

 # cascade会导致删除和更新被关联的表时,同步删除关联表中相应外键下的记录,否则不能删除被关联表,除非先删除关联表或修改关联表中外键

实际应用中,尽量少用foreign key

可以有复合外键,前提是引用的是复合主键

 

posted @ 2018-03-13 17:14  Claire_xu  阅读(756)  评论(0编辑  收藏  举报