数据库基础学习3——高级操作
数据库基础学习3——高级操作
外键的引入与级联
外键是关联几个表的关键,通过外键建立几个表的关联关系。
创建外键关联的表
create table scores( id int primary key auto_increment, stuid int, subid int, score decimal(5,2), foreign key(stuid) references students(id), foreign key(subid) references subjects(id) );
添加级联的相关操作:
alter table scores add constraint stu_sco foreign key(stuid) references students(id) on delete cascade;
级联操作的类型:
-
restrict(限制):默认值,抛异常
-
cascade(级联):如果主表的记录删掉,则从表中相关联的记录都将被删除
-
set null:将外键设置为空
-
no action:什么都不做
连接查询
将几张表的信息一次性查出来放在一起显示
select students.sname,subjects.stitle,scores.score from scores inner join students on scores.stuid=students.id inner join subjects on scores.subid=subjects.id;
连接查询分类:
-
表A inner join 表B:表A与表B匹配的行会出现在结果中
-
表A left join 表B:表A与表B匹配的行会出现在结果中,外加表A中独有的数据,未对应的数据使用null填充
-
表A right join 表B:表A与表B匹配的行会出现在结果中,外加表B中独有的数据,未对应的数据使用null填充
练习:
-
查询学生的姓名、平均分
-
select students.sname,avg(scores.score) from scores inner join students on scores.stuid=students.id group by students.sname;
-
查询男生的姓名、总分
-
select students.sname,avg(scores.score) from scores inner join students on scores.stuid=students.id where students.gender=1 group by students.sname;
-
查询科目的名称、平均分
-
select subjects.stitle,avg(scores.score) from scores inner join subjects on scores.subid=subjects.id group by subjects.stitle;
-
查询未删除科目的名称、最高分、平均分
select subjects.stitle,avg(scores.score),max(scores.score) from scores inner join subjects on scores.subid=subjects.id where subjects.isdelete=0 group by subjects.stitle;
自关联查询
跨表查询其实挺耗时间,对于数据结构相似且数据量不大的表,我们将它们放在一张表里面操作。
eg:省市县表
create table areas( id int primary key, atitle varchar(20), pid int, foreign key(pid) references areas(id) );
查询山西省下面的市:
select city.* from areas as city inner join areas as province on city.pid=province.id where province.atitle='山西省';
查询市的名称为“广州市”的所有区县
select dis.*,dis2.* from areas as dis inner join areas as city on city.id=dis.pid left join areas as dis2 on dis.id=dis2.pid where city.atitle='广州市';