MySQL约束条件

博客介绍了数据库表的多种约束,如not null、unique、auto_increment、primary key等,说明了主键的特性及联合主键的规则,还讲解了外键及级联更新、级联删除的用法,最后给出表的关联练习题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

not null

# not null (是否可以为空)
create table stu(id int(10),
name char(12) not null,
sex enum('male','female')
);

not null + default(默认值)

create table stu2(
id int,
name char(12) not null,
phone char(11),
sex enum('male','female') not null default 'male'
);

unique(唯一)

create table stu3(
id int,
name char(12),
ident char(18) unique
);

unique(联合唯一)

ip + port
192.168.16.13  mysql 3306
192.168.16.13  kugou 8080
192.168.16.13  flask 5000
192.168.16.15  mysql 3306
192.168.16.16  mysql 3306

create table service(
id int,
ip char(15),
name char(15),
port int(5),
unique(ip,port)
);

auto_increment

自增的条件(这一列必须是数字,这一列必须是uniuqe)

create table userinfo(
  id int unique auto_increment,
  name char(12),
  password char(32)
);

primary key(主键)

primary key(主键)  ==  not null 非空 + unique 唯一 

create table userinfo3(
  id int unique,
  username char(18) not null unique,
  password char(32),
  ident char(18) not null unique
);

一张表中只能有一个主键 : 主键从约束的角度上来说 就是非空且唯一的
只不过,非空+唯一可以设置多个字段,但是主键只能给一个表中的一个字段设置
(一般情况下,我们给id字段设置为主键,不允许一张表不设置主键)

create table pri2(
  id1 int primary key,
  id3 int unique not null
);

联合主键

约束多个字段各自不能为空,并且联合唯一

create table pri4(
    id1 int,
    num int,
    primary key(id1,num)
);

外键

foreign Key(被关联的项) references 被关联的表(待关联的项)

# 表2 班级表 cid class_name
create table clas(
    cid int primary key,
    class_name char(20)
 );
 
# 表1 学生表 id name class_id
create table stu(
    id int primary key ,
    name char(18),
    class_id int,
    foreign Key(class_id) references clas(cid)
 );

级联更新,级联删除

(关联后可以修改也可以删除)on update cascade on dalete cascade

create table stu(
    id int primary key ,
    name char(18),
    class_id int,
    foreign Key(class_id) references clas(cid)
    on update cascade on dalete cascade
 );

练习题:表的关联练习

转载于:https://www.cnblogs.com/songzhixue/p/11159852.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值