笛卡尔积
* 有两个集合,他们里面的额元素的所有组合情况就是迪卡尔积
多表查询
* 内连接查询
1.隐式内连接:
2.显式内连接:
select 字段列表 from 表1 inner join 表2 on 条件
inner 可省略
3.内连接的使用步骤
1) 确定查询哪些表
2) 确定表连接的条件
3) 确定查询的条件
4) 确定查询的字段
* 外连接查询
1.左外连接:
select 字段列表 from 表1 left [outer] join 表2 on 条件
查询的是左表的所有数据和其交集部分
2.右外连接:
* 子查询
-- 删除和修改的时候 子查询中不允许直接出现 删除的表或者修改的表
-- 解决方案:使用临时表
*子查询的概念:
1) 一个查询的结果做为另一个查询的条件
2) 有查询的嵌套,内部的查询称为子查询
3) 子查询要使用括号
1.子查询结果只要是单行单列,肯定在 WHERE 后面作为条件,父查询使用 : 比较运算符,如 : > 、<、<>、 =等
2.子查询结果是单例多行,结果集类似于一个数组,父查询使用 IN 运算符
3.子查询结果只要是多列,肯定在 FROM 后面作为表
SELECT 查询字段 FROM (子查询) 表别名 WHERE 条件;
子查询作为表需要取别名,否则这张表没有名称则无法访问表中的字段
*子查询小结:
子查询结果只要是单列,则在 WHERE 后面作为条件
子查询结果只要是多列,则在 FROM 后面作为表进行二次查询
多表查询案例:
teacher 教师表
student 学生表
cource 课程表
studentcource 选课表 学生和课程的关系表
CREATE TABLE teacher (
id int(11) NOT NULL primary key auto_increment,
name varchar(20) not null unique
);
CREATE TABLE student (
id int(11) NOT NULL primary key auto_increment,
name varchar(20) NOT NULL unique,
city varchar(40) NOT NULL,
age int
) ;
CREATE TABLE course(
id int(11) NOT NULL primary key auto_increment,
name varchar(20) NOT NULL unique,
teacher_id int(11) NOT NULL,
FOREIGN KEY (teacher_id) REFERENCES teacher (id)
);
CREATE TABLE studentcourse (
student_id int NOT NULL,
course_id int NOT NULL,
score double NOT NULL,
FOREIGN KEY (student_id) REFERENCES student (id),
FOREIGN KEY (course_id) REFERENCES course (id)
);
insert into teacher values(null,'关羽');
insert into teacher values(null,'张飞');
insert into teacher values(null,'赵云');
insert into student values(null,'小王','北京',20);
insert into student values(null,'小李','上海',18);
insert into student values(null,'小周','北京',22);
insert into student values(null,'小刘','北京',21);
insert into student values(null,'小张','上海',22);
insert into student values(null,'小赵','北京',17);
insert into student values(null,'小蒋','上海',23);
insert into student values(null,'小韩','北京',25);
insert into student values(null,'小魏','上海',18);
insert into student values(null,'小明','北京',20);
insert into course values(null,'语文',1);
insert into course values(null,'数学',1);
insert into course values(null,'生物',2);
insert into course values(null,'化学',2);
insert into course values(null,'物理',2);
insert into course values(null,'英语',3);
insert into studentcourse values(1,1,80);
insert into studentcourse values(1,2,90);
insert into studentcourse values(1,3,85);
insert into studentcourse values(1,4,78);
insert into studentcourse values(2,2,53);
insert into studentcourse values(2,3,77);
insert into studentcourse values(2,5,80);
insert into studentcourse values(3,1,71);
insert into studentcourse values(3,2,70);
insert into studentcourse values(3,4,80);