赞
踩
MySQL
表的增删改查(进阶)约束类型
NOT NULL - 指示某列不能存储 NULL 值。(如果尝试往这里插入空值,就会直接报错)
-- 示例 --
-- 重新设置学生表结构
drop table if exists student;
create table student (id int not null, sn int, name varchar(20), qq_mail varchar(20));
UNIQUE - 保证某列的每行必须有唯一的值。(如果尝试往这里插入重复的值,就会直接报错)
-- 重新设置学生表结构
drop table if exists student;
create table student (id int not null, sn int unique, name varchar(20), qq_mail varchar(20));
DEFAULT - 规定没有给列赋值时的默认值。(默认的默认值为NULL)
-- 重新设置学生表结构
drop table if exists student;
create table student (id int not null, sn int unique, name varchar(20) default '匿名', qq_mail varchar(20));
PRIMARY KEY - NOT NULL 和 UNIQUE 的结合。确保某列(或两个列多个列的结合)有唯一标识,有助于更容易更快速地找到表中的一个特定的记录。
(主键约束,相当于数据的唯一身份标识,类似于身份证号码/手机号码)
drop table if exists student;
create table student (id int primary key, sn int unique, name varchar(20) default '匿名', qq_mail varchar(20));
对于整数类型的主键,常配搭自增长auto_increment来使用。插入数据对应字段不给值时,使用最大值+1。
-- 主键是 NOT NULL 和 UNIQUE 的结合,可以不用 NOT NULL
id int primary key auto_increment,
自增主键也是可以手动指定id的,一旦指定过后就是从指定后的数往后开始自增了.
FOREIGN KEY - 保证一个表中的数据匹配另一个表中的值的参照完整性。
(外键约束: 描述两个表之间的关联关系,表1的数据必须在表2中存在)
-- FOREIGN KEY:外键约束,外键用于关联其他表的主键或唯一键,语法:
foreign key (字段名) references 主表(列)
-- 创建班级表,有使用MySQL关键字作为字段时,需要使用``来标识
drop table if exists class;
create table class(classId int primary key auto_increment, name varchar(20));
insert into class values (null, 'java100');
insert into class values (null, 'java101');
insert into class values (null, 'java102');
select * from class;
创建学生表student,一个学生对应一个班级,一个班级对应多个学生。使用id为主键,classId为外键,关联班级表id
drop table if exists student;
create table student(studentId int primary key auto_increment, name varchar(20),
classId int, foreign key (classId) references class(classId));
insert into student values (null
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。