数据库约束命令

mysql中:

id中存在auto_increment

CREATE TABLE u_user(
 id int PRIMARY KEY auto_increment,
 u_name VARCHAR(10) NOT NULL UNIQUE,
 age int CHECK(age>0 && age<=120),
 u_status char(1) DEFAULT(1),
 gender char(1)
);
INSERT into u_user(u_name,age,u_status,gender)VALUES("李明",20,"1","男"),("王丽",18,"1","女");

外键约束:

-- 创建主表(班级表)
create table class(
	c_id int(4) primary key auto_increment,
	c_name varchar(10)
);
-- 班级表添加数据
insert into class values(NULL, 'xg1901'), (NULL, 'xg1902');

-- 创建从表(学生表)
create table stu_table(
	s_id int PRIMARY key auto_increment,
	s_name varchar(10) not null,
	s_sex char(1) check(s_sex = '男' or s_sex = '女'),
	s_age int(3) check(s_age > 0 and s_age < 100),
	c_id int(4),
	
	-- 创建时添加表级外键约束
	constraint fk_c_id  foreign key (c_id) references class(c_id)
);
-- 创建从表(学生表)
create table stu_table(
	s_id int PRIMARY key auto_increment,
	s_name varchar(10) not null,
	s_sex char(1) check(s_sex = '男' or s_sex = '女'),
	s_age int(3) check(s_age > 0 and s_age < 100),
	c_id int(4) 
	
	#创建时添加外键
	CONSTRAINT fk_c_id FOREIGN KEY(c_id) REFERENCES class(c_id)
);
-- 学生表中插入数据
insert into stu_table values (NULL, '香菱', '女', 18, 1);
insert into stu_table values (NULL, '行秋', '男', 18, 2);
insert into stu_table values (NULL, '胡桃', '女', 16, 2);
insert into stu_table values (NULL, '班尼特', '男', 18, 1);


不能删除外键:

删除外键语句:

ALTER TABLE stu_table drop foreign key fk_c_id;

删除或更新外键(级联操作)

使用cascade,当父表删除或更新对象记录时,首先检查该记录是否有对应外键,若有,则也删除或更新外键在子表中的记录。

set null:当父表删除或更新对象记录时,首先检查该记录是否有对应外键,若有,则设置子表中该外键的值为null。

父表/主表:含有被依赖的字段的表。

子表/从表:使用外键约束的表。

原始表:

使用语句:

#删除或更新外键
ALTER TABLE stu_table ADD CONSTRAINT fk_c_id FOREIGN KEY(c_id) REFERENCES class(c_id) ON UPDATE CASCADE ON DELETE CASCADE;

  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值