小例子: create table test( id int auto_increment, name varchar(50) not null, idcard varchar(20), address varchar(50), unique(idcard), primary key(id, name) ); 当违反约束的时候插入不成功,会报错。 测试插入情况: insert into test( id, name, idcard, address ) values ( 1, 'aaa', '12213123', 'beijing' ), ( 1, 'bbbb', '232423', 'shanghai' ); 下面的记录无法插入,违反主键约束 insert into test( id, name, idcard, address ) values ( 1, 'aaa', '12213123', 'beijing' ); 违反的是非空约束 insert into test( id, name, idcard, address ) values ( 2, null, '12213123', 'beijing' ); 违反唯一约束 insert into test( id, name, idcard, address ) values ( 2, 'cccc', '12213123', 'beijing' );
小例子: 为teachers表的name列添加表级的唯一约束 alter table teachers add unique(name); 丢弃表级唯一约束 alter table teachers drop index `name`; 和 alter table teachers drop key `name`; 以下语句无法丢弃表级约束 alter table teachers modify name varchar(25);
小例子: 为phone列添加列级的非空约束 alter table teachers change phone phone varchar(15) not null; 丢弃列级约束 alter table teachers modify phone varchar(15) null;
小例子: 教师表,班主任要引用老师表的主键。 create table classes ( id int auto_increment, name varchar(20) unique, master int, classroom int not null, begindate datetime, primary key(id), foreign key(master) references teachers(id) ); +----+--------+--------+------+--------------+---------------------+--------------+ | id | name | gender | age | phone | birthday | home | +----+--------+--------+------+--------------+---------------------+--------------+ | 1 | 张老师 | 男 | 40 | 135234234234 | 1976-05-02 10:01:01 | 北京通州32号 | | 2 | 李老师 | 女 | 40 | 135234234234 | 1976-05-02 10:01:01 | 北京昌平32号 | | 3 | 刘老师 | 男 | 30 | 135234234234 | 1986-05-02 10:01:01 | 北京朝阳32号 | | 4 | 闫老师 | 女 | 25 | 124234234 | 1990-01-02 00:00:00 | 北京西城 | +----+--------+--------+------+--------------+---------------------+--------------+ 插入4值时,需要先到母表中进行检索,若可以找到数据,插入成功 insert into classes ( name, master, classroom, begindate ) values ( 'H50826', 4, 232, now() ); 插入400值时, 需要先到母表中进行检索, 如果没有找到数据,则插入失败 insert into classes ( name, master, classroom, begindate ) values ( 'JavaEE0826', 400, 333, now() ); 插入成功 insert into classes ( name, master, classroom, begindate ) values ( 'Android0826', 4, 333, now() ); 插入成功 insert into classes ( name, master, classroom, begindate ) values ( 'JavaEE1117', 1, 101, '2016-7-17' );
测试外键约束 当母表中的记录被引用时, 不能删除这条记录 先把子表中的相应记录删除,才能再删除这条记录 insert into teachers ( id, name, gender, age, phone, birthday, home ) values ( 4, '奈老师', '女', 40, '135234234234', '1976-5-2 10:1:1', '北京京州32号' ); 把子表的外键约束丢弃 alter table classes drop foreign key classes_ibfk_1;
小例子: 级联删除 alter table classes add constraint my_fk foreign key(master) references teachers(id) on delete cascade on update cascade; 级联置null alter table classes add constraint my_fk foreign key(master) references teachers(id) on delete set null on update set null;