当前位置:   article > 正文

MySQL表的增删改查(进阶)_drop table if exists student;

drop table if exists student;

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));   
  • 1
  • 2
  • 3
  • 4
  • 5

在这里插入图片描述

UNIQUE - 保证某列的每行必须有唯一的值。(如果尝试往这里插入重复的值,就会直接报错)
-- 重新设置学生表结构
drop table if exists student;
create table student (id int not null, sn int unique, name varchar(20), qq_mail varchar(20));
  • 1
  • 2
  • 3
  • 4

在这里插入图片描述

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));
  • 1
  • 2
  • 3
  • 4

在这里插入图片描述

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));
  • 1
  • 2
  • 3
  • 4

对于整数类型的主键,常配搭自增长auto_increment来使用。插入数据对应字段不给值时,使用最大值+1。

-- 主键是 NOT NULL 和 UNIQUE 的结合,可以不用 NOT NULL
id int primary key auto_increment,
  • 1
  • 2

自增主键也是可以手动指定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;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

在这里插入图片描述

创建学生表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
  • 1
  • 2
  • 3
  • 4
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/490631
推荐阅读
相关标签
  

闽ICP备14008679号