案例表:
- drop table if exists classes;
- create table classes (
- id int primary key auto_increment,
- name varchar(20)
- );
- insert into classes (name) values
- ('计算机1班'),
- ('自动化2班'),
- ('机械3班');
-
- drop table if exists student;
- create table student (
- id int primary key auto_increment,
- name varchar(10),
- classes_id int,
- foreign key (classes_id) references classes(id)
- );
- insert into student (name,classes_id) values
- ('小花',2),
- ('小张',1),
- ('小贺',1),
- ('小方',3),
- ('小乔',3);
-
- drop table if exists course;
- create table course (
- id int primary key auto_increment,
- name varchar(20)
- );
- insert into course (name) values
- ('java程序设计'),
- ('大学英语'),
- ('高等数学'),
- ('数据结构'),
- ('工程制图');
-
- drop table if exists score;
- create table score (
- id int primary key auto_increment,
- score decimal(3,1),
- student_id int,
- course_id int,
- foreign key (student_id) references student(id),
- foreign key (course_id) references course(id)
- );
- insert into score (score,student_id,course_id) values
- -- 小花
- (98.5,1,3),(80,1,5),
- -- 小张
- (99,2,1),(95,2,2),(96,2,3),(90,2,4),(93,2,5),
- -- 小贺
- (85,3,1),(86,3,2),(86,3,3),(95,3,4),
- -- 小方
- (70,4,3),(65,4,5),
- -- 小乔
- (65,5,5),(67,5,3),(68,5,2);
联合查询其实就是把多张表融合在一起查询,也就是针对笛卡尔积进行查询。关联查询可以对关联表使用别名。