MYSQL_约束条件

约束Constraint:

对插入表中字段的数据起到一定的条件限制。

约束分五种:
主键约束:primary key
要求作为主键的字段的字段值非空且唯一
非空约束: not null
要求:有非空约束的字段不可以为null值。
唯一性约束:unique
要求有唯一性约束的字段不可以重复,但是可以为null.
检查性约束: check(条件)— check(gender in(‘f’,’m’))
要求在插入数据时必须符合字段的检查条件,但是可以为null
PS:在mysql中chack无效,一般使用枚举gender enum('f','m'),来代替gender varchar(1) check(gender in('f','m'))
外键约束: foreign key
要求:有外键约束的字段A必须依赖于另外一个字段B,
字段B要有主键约束。
字段A的值,要么是null, 要么必须是字段B里的值。

例:

empno int *primary key*,
ename varchar(20) *not null*,
idcard varchar(18) *unique*,
gender *enum('f','m')*,
mgr int *foreign key(mgr) references t_05(empno)*
建表后修改约束:

添加约束:

alter table tableName
add constraint <约束名 约束条件>;

删除约束:

alter table tableName
drop constraint <约束名 约束条件>;

修改emp表中的empno字段为主键约束和自增
方法1:
alter table emp change empno empno int primary key auto_increment;

方法2:
alter table emp add constraint cons_empno primary key(empno);
alter table emp modify empno int auto_increment;

序列:

作为主键的字段,通常不是表中的主要信息,可以用来当成信息记录的序号。序号最好是有序的序列。

auto_increment 关键字,用来对有主键约束的字段做自增操作。

用法:
create table tname(
tid int primary key auto_increment,
……
);

last_insert_id() 函数:
作用:获取序列最后一次插入的值。
用法:select last_insert_id();

猜你喜欢

转载自blog.csdn.net/yc_hen/article/details/82724454