2025-10-12-数据库约束
类型
| 关键字 | 作用 |
|---|---|
Not Null | 非空约束,修饰对象不能为空 |
Unique | 唯一约束,修饰对象不能重复 |
Primary Key | 主键,Not Null 与 Unique 的结合,通常配合 auto_increment(自增) |
Foreigin Key | 外键,修饰父表的那一列需要唯一 |
Check | 自定义约束,需要 MySQL 8.0.14 以上才能使用 |
Foreigin Key
创建商品表与货物表
在里面列举一些正确/错误的插入/删除
SQL
drop table if exists `order`;
drop table if exists `goods`;
create table `goods` (
goods_id int primary key auto_increment,
`name` varchar(20),
price decimal(10,4)
);
-- 这个一般还需要买家 id 但是为了方便就不写了
create table `order` (
order_id int primary key auto_increment,
goods_id int,
nums int,
foreign key (goods_id) references goods(goods_id)
);
insert into goods(`name`, price)
values ('苹果', 3.2),('香蕉', 2.5),('桃子', 4.3);
insert into `order`(`goods_id`, nums)
values (1, 10),(2, 2),(2, 6);
delete from goods where goods_id = 3;
-- 错误插入
insert into `order`(`goods_id`, nums)
values (5, 10);
-- 错误删除 应该把订单表中有关 goods_id = 1 删除完后才能执行这个语句
delete from goods where goods_id = 1;Check
以学生表为例
要求:
- age >= 17
- gender = '男' or gender = '女'
SQL
drop table if exists `student`;
create table student (
id int primary key auto_increment,
name varchar(20),
age int,
gender varchar(1),
check (age >= 17),
check (gender = '男' or gender = '女')
);
-- 正确插入
insert into student values
(null, '小明', 18, '男'),
(null, '小美', 20, '女');
-- 错误插入
insert into student values
(null, '小美', 10, '女');
insert into student values
(null, '小美', 20, '直');