MySQL约束

MySQL约束

# primary key(主键)

// 用于唯一的表示表行的数据,当定义主键约束后,该列不能重复
字段名 字段类型 primary key
-- 细节:
-- 1.主键不能重复且不能为null

-- 2.一张表最多只能由一个主键,但可以是复合主键,一起不能相同
create table t
				(id int,
         `name` varchar(32),
         email varchar(32),
         primary key (id,`name`) -- 这里就是复合主键
        );

-- 3.主键的定义由两种
-- ① 字段 字段类型 primary key
-- ② create table 表名(...,  primary key(列名));

-- 4.使用desc可以看到primary key的情况
desc 表名
# unique(唯一)

// 被表示的列不能重复,可以为null
字段名 字段类型 unique
-- 细节:
-- 1.如果没有指定not null,则unique字段可以由多个null

-- 2.一张表可以有多个unique字段
  • 外键约束

img

img

此时插入一个class_id为300的数据,因为班级中没有id为300的数据,所以会插入失败

此时如果班级表中删除id为200的数据,会报错,因为需要先删除学生表中class_id为200的数据

# check

// 强制行数据必须满足的条件,假定在sal列上定义了check约束,并要求sal列值在1000~2000之间,插入数据不在就会出错
列名 类型 check(check条件)
check(sal > 1000 and sal < 2000)

商店表设计

# 练习

/**
商品goods(商品号goos_id,商品名goods_name,单价unitprice,商品类别category,提供商provider)
客户customer(客户号customer_id,姓名name,住址address,电邮email,性别sex,身份证card_id);
购买purchase(购买订单号order_id,客户号customer_id,商品号goods_id,购买数量nums);
*/

建表,在定义中要求声明[进行合理设计]
// 每个表的主外键
// 客户的姓名不能为空值
// 电邮不能重复
// 客户的性别[男|女]
// 单价unitprice在1.0-9999.99之间check

-- 商品表
create table goods(
goods_id int primary key auto_increment, -- 主键自增长
goods_name varchar(100) not null default '',
unitprice double not null default 0 check(unitprice > 1.0 and unitprice < 9999.99),
category int not null defult 0,
provider varchar(100) not null default '');

-- 顾客表
create table customer(
customer_id int primary key,
`name` varchar(100) not null default '',
address varchar(1024) not null default '',
email varchar(100) unique not null default '',
sex enum('男','女') not null,
card_id int);

-- 购物表
create table purchase(
order_id int primary key,
customer_id int not null default 0,
goods_id int not null default 0,
nums int not null default 0,
foreign key(customer_id) references customer(customer_id),
foreign key(goods_id) references goods(goods_id)
);
y(customer_id) references customer(customer_id),
foreign key(goods_id) references goods(goods_id)
);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值