1.外键约束
对于多张表来说,如果一个表的某个标题例如teacher对应另外一张表的标题student是有对应关系的,这可以添加外键约束,来禁止擅自删除这两个标题。
创建约束
将teacher和student表相关联,并且以id和stu_id为外键,创建约束时,相关联的标题数据类型一定要一致。
foreign key (stu_id) references teacher(id);此为创建表时添加外键
当创建表是没有添加外键,现在想添加
alter table student add constraint student foreign key(stu_id) references teacher(id); reference的这个键,必须为那个表的主键,被参考的键不能是主键,其中主表是参考的表
删除外键约束
alter table student drop foreign key studnet;
级联操作
级联操作是将外键绑定在一块,如果主键被删除,那么子键将同时被删除
alter table student add constraint student foreign key(stu_id) references teacher(id) on delete cascade ;
alter table student add constraint student foreign key(stu_id) references teacher(id) on delete set null; 对主键进行删除时,子健的值全部变为null而不是删除
多表查询-链接查询
同时显示多张表
select * from student,teacher; 显示的时候会将所有对应的都显示出来,信息是多的,所以要进行筛选,inner join/left join/right join/full join
select * from student,teacher where teacher.id=student.stu_id; 筛选两者通过主键链接冰箱等的值
内联查询
select * from student inner join teacher on teacher.id=student.stu_id; 查询a和b表中值相等的行
外联查询
select * from student left join teacher on student.stu_id=teacher.id; 以左侧的表为标准,如右侧没有对应则显示null,如果是一对多则显示多个行
复合查询和子查询
将查询语句的结果嵌套到另外一个查询语句中,为另一个查询语句提供条件
select * from student where stu_id in (select stu_id from student where stu_id >2);
exists==对后面的语句进行判定,如果正确则返回true