mysql——约束

目录

1.主键约束

2.自增约束

3.唯一约束

4.非空约束

5.默认值

6.注释

7.数据类型约束

8.外键约束


1.主键约束

primark key

-- 基本模式
create table temp( 
id int primary key,
name varchar(20)
);

-- 组合模式
create table temp(
id int ,
name varchar(20),
pwd varchar(20),
primary key(id, name)
);

-- 删除主键约束
alter table temp drop primary key;

-- 添加主键约束
alter table temp add primary key(id,name);

-- 修改主键约束
alter  table temp modify id int primary key;

2.自增约束

auto_increment

3.唯一约束

unique

-- 创建表时设置,表示用户名、密码不能重复
    create table temp(
    id int not null ,
    name varchar(20),
    password varchar(10),
    unique(name,password)
);


-- 添加唯一约束
alter table temp add unique (name, password);


-- 修改唯一约束
alter table temp modify name varchar(25) unique;

-- 删除唯一约束
alter table temp drop index name;

4.非空约束

not null

5.默认值

default "值"

6.注释

comment

7.数据类型约束

8.外键约束

foreign key

  • 1.数据类型不一样
  • 2.某个表里已经有记录了
  • 3.两个表的引擎不一样,查看表的引擎语句:show table status from 数据库名 where name='表名';
  • 4.要设置外键的字段不能为主键
  • 5.改建所参考的字段必须为主键
  • 6.两个字段必须具有相同的数据类型和约束
/*
 引用完整性约束-外键(foreign key)
 创建外键的方式
 1 在建表时直接指定
   在引用了别的表字段的表中添加外键约束
		constraint 外键名 foreign key(当前表字段) references 其他表(字段)
 2 建好表后再指定
   alter table 表名 add constraint 外键名 foreign key (字段) references 其他表(字段)
*/
create table stu(
 sid int primary key auto_increment comment '学生主键',
 sname varchar(10) comment '学生姓名',
 age int comment '学生年龄'
);
create table course(
 cid int primary key auto_increment comment '课程主键',
 cname varchar(10) comment '课程名称',
 sid int comment '关联学生表id',
    /*
    	在创建表时添加外键sid
    */
 constraint fk_course_stu foreign key(sid) references stu(sid)
-- 	foreign key(cid) references b(cid)
);


/*
	表创建完成后添加外键
	constraint fk_course_stu (设置外键名字)可以省略
*/
alter table course add constraint fk_course_stu foreign key (sid) references stu(sid);
-- alter table a add  foreign key(cid) references b(cid);


/*
	删除外键
*/
alter table course drop foreign key fk_course_stu

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值