mysql基础

92 阅读1分钟

1 数据表的关联关系

  • 主键关联
  • 外键关联
  • 一对多 在多的一端建立外键
  • 多对多 创建关系表来维护多对多关联-定义两外键,分别和数据表关联

2 外键约束

  • 2.1 创建班级表
create table classes( 
 class_id int primary key auto_increment,
 class_name varchar(40) not null unique,
 class_remark varchar(200)
 );
 
  insert into classes ( class_name ,class_remark) values ('python3 ',',,,');
  • 2.2 创建学生表
create table students(
stu_id char(8) not null,
stu_name char(8) not null,
stu_gender char(2) not null,
stu_age int not null,
cid int,
constraint fk_students_classes foreign key(cid) references classes( class_id)
);

 insert into students(stu_id,stu_name,stu_gender,stu_age,cid) values('20020418','liuyang','女',20,4);

  • 2.3 创建外键 constraint name foreign key(cid) references classer(class_id); 在创建表表以后添加

  • 2.4 创建表以后再加外键约束

    • alter table students add constraint fk_students_classes foreign key(cid) references classes(class_id);
  • 2.5 update students set cid=NUll where cid = 1; 修改之前要把外键链接的改为null

  • update classes set class_id = 5 where class_name='lichang';

  • 2.6 级联操作

    • 添加外键的时候添加级联修改和级联删除

3 连接查询

  • 3.1 从多个表里面查询数据(一般)
    • inner join
    • left join 左连接
    • right join 右链接