1.多对多的表:
create table student
(
id int primary key auto_increment comment '主键ID',
name varchar(10) comment '姓名',
no varchar(10) comment '学号'
) comment '学生表';
insert into student values(null,'杨丙阳','1520213586'),(null,'段俊','1520213587'),(null,'肖晟','1520213588'),(null,'曾斌','1520213589');
create table course(
id int primary key auto_increment comment '主键ID',
name varchar(10) comment '课程名称'
)comment '课程表';
insert into course values(null,'Java'),(null,'Python'),(null,'MySQL'),(null,'C++');
create table student_course(
id int primary key auto_increment comment '主键',
studentid int not null comment '学生ID',
courseid int not null comment '课程ID',
constraint fk_coueseid foreign key (courseid) references course(id),
constraint fk_studentid foreign key (studentid) references student(id)
)comment '学生课程中间表';
insert into student_course values(null,1,1),(null,1,2),(null,1,3),(null,2,2),(null,2,3),(null,3,4);
2.连接:
需要用到的两张表:
消除笛卡尔积:
#多表查询--笛卡尔积
select *from company,dept;
#消除笛卡尔积
select *from company,dept where company.dept_id=dept.id;
内连接:
/*连接查询--内连接*/
#隐式内连接 select 字段列表 from 表1,表2 where 条件
select company.name,dept.name from company ,dept where company.dept_id=dept.id;
#显式内连接 select 字段列表 from 表1(inner) join 表2 on 连接条件
select company.name,dept.name from company inner join dept on company.dept_id=dept.id;
外连接:
#左外连接 select 字段列表 from 表1 left [outer] join 表2 on 条件
select c.*,d.name from company c left join dept d on c.dept_id=d.id;
#右外连接 select 字段列表 from 表1 right [outer] join 表2 on 条件
select c.name,d.* from company c right join dept d on c.dept_id=d.id;
自连接:
*自连接:一张表自己使用多次,可以是内连接,也可以外连接
select 字段列表 from 表A 别名A join 表A 别名B on 条件*/
#查询员工及其所属领导的名字
select a.name,b.name from company a,company b where a.managerid=b.id;
#查询所有员工company及其领导的名字,如果员工没有领导,也需要查询
select a.name'员工',b.name'领导' from company a left join company b on a.managerid=b.id;