- alter table 表名 character set utf8; 修改表编码
- 主键约束(Primary key)
- 每个表格内 只能有一个列被设置为主键约束
- 主键约束通常是用来标记表格中数据的唯一存在
- 主键约束要求当前的列 不能为null值
- 主键约束要求当前的列 值是唯一存在的 不能重复
alter table 表名 add constraint 约束名 约束类型 (列);
alter table myclass add constraint pk_myclass primary key(classid);
desc myclass; —- description 描述
show keys from myclass
发现自己定义的主键名字没有用上 可以简写
alter table 表名 add primary key (classid);
添加主键之后若想要让主键自增 可以做相应的设计
alter table myclass modify classid int(4) auto_increment;
alter table myclass change classid classid int(4) auto_increment;
alter table myclass auto_increment = 10;
去掉自增
alter table myclass modify classid int(4);
删除主键约束
alter table myclass drop primary key;
注意:删除主键约束以后 不重复的特性取消了 但是非空的特性还没有取消
alter table myclass modify classid int(4) null;
- 唯一约束(Unique [Key])
- 主键约束在表格中只能存在一个
- 可以为表格中的耨一个列添加唯一约束 约束与主键类似
- 唯一约束表示的是列的值 不能重复 可以为空
- 唯一约束在表格中可以存在多个列
- alter table myclass add constraint 约束名 约束类型(列名);
- alter table myclass add constraint uk_myclass unique key(loc);
- alter table myclass add unique key(loc); 约束名默认的列名
- 删除唯一约束
- alter table myclass drop index 约束名;
- ———————————————————————
alter table myclass add unique (loc); - alter table myclas drop index loc;
- 非空约束
- 在表格中的某一个列上添加非空约束3
- 当前列的值不能为null值
- alter table 表 modify cname varchar(20) not null;
- alter table 表 change cname cname varchar(20) not null;
- //不能为空还不想空着
- alter table myclass modify cname varchar(20) not null default ‘wyh is good’;
- alter table myclass change cname cname varchar(20) not null default ‘wyh is good’;
- 外键约束
- 表格中可以有多个列被设置为外键约束
- 当前列的值可以为空 可以重复
- 当前列的值不能随便的填写 值去另外一张表格内寻找
- 外键是当前列的值受到另外一张表格某一个列的影响
- 另外一张表格的列 是唯一约束(主键 唯一)
- 添加外键约束(Foreign Key)
- **alter table 表名字 add constraint fk当前表关联表 foreign key(列) references 表名(列名)**
- 删除外键约束
- alter table 表名字 drop foreign key 约束名字;
- alter table student drop foreign key fk_student_myclass;
- 删除之后发现没有删掉;
- 注意:通过上述语句其实已经将外键约束删掉了
- 自动在当前表格内添加一个新的key
- 需要再次手动将这个生成的key删掉 外键约束才是真的删除干净
- alter table 表名字 drop key 约束名字
- alter table student drop key fk_student_myclass;
- alter table 表名字 drop foreign key 约束名字;
- alter table student add foreign key(列) references 另一个表(列);
- 注意: 如果是简写的效果添加外键, 外键的名字不是默认列名: student_ibfk_1;
- alter table student drop foreign key student_ibfk_1;
- alter table student drop key classid;
- show create table student;
- alter table student drop key
- 添加外键约束(Foreign Key)
- 检查约束(不好用)(Check)
- 列在存执的时候做一个细致的检查
- altertable student add constraint ck_sage_check(sage>15 and sage<30);
- alter table student modify sage sage int(4);
