MySQL007----多表查询

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;

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值