mysql中的多表查询

一:笛卡尔积

表示为:XY
例如:A表中有m行,B表中有n行,那么A和B的笛卡尔积为 m
n 行。

二:多表查询

1.内连接:查询A和B公共部分
在这里插入图片描述

(1)
select column,sum(column)
from table1 join(inner/cross) table2
on 过滤条件(将所有的笛卡尔积无用信息过滤掉)
group by column
where 条件查询

(2)
select column,sum(column)
from table1,table2
where 条件语句
group by column;

eg:查询张三的成绩和名字
(1)select username,score
from student join course_score
on student_id=student.id
where name=‘张三’;

(2)select username,score
from student,course_score
where student_id=student.id
and name=‘张三’;

2.外连接:查询A的所有部分或者B的所有部分
在这里插入图片描述

(1)左(外)连接:查询A的所有信息
select * from A left join B
on 连接条件
where 查询条件

eg:(两张表)
select* from student
left join course_score
on student.id=student_id;

eg:(三张表)
select s.username,s.sno,s.mail,c.name,st.score
from student s
left join course_score st on s.id=st.student_id
left join course c on c.id=st.course_id;

(2)右(外)连接:查询B的所有信息
select * from B right join A
on 连接条件
where 查询条件

*注意:
(1)内连接on可以省略,外连接on不能省略
内连接不加on,会显示所有笛卡尔积,外连接不加on会报错
(2)内连接和外连接中on的执行效果不一样
a.内连接中on对全局起关联,如join…on…and 条件语句 ,and的条件在全局执行,对所有表起作用
b.外连接中on只对自己加入的表起限制,如left join…on…and条件语句,on…and的条件不能对主表起作用,只对left join 后加的次表起作用
(3)在外连接中,on和where的作用不同
在外连接查询,如果有多个查询条件,将查询条件在where 中,on中只写笛卡尔积的过滤条件

3.自连接
指同一张表连接自身进行查询
select *
from table_name st1,table_name st2
where st1.id=st2.id;

eg:查询英语成绩大于计算机成绩的同学信息
select* from course_score st1, course_score st2
(同一张成绩表命名为不同名)
where st1.student_id=st2.student_id
(选取同一个人英语成绩和计算机成绩)
and st1.course_id=1 and st2.course_id=2
(让st1中的课程为英语,st2的课程为计算机)
and st1.score>st2.score;
(英语成绩大于计算机成绩)

4.子查询

eg:查找张三班级的同学信息
select *
from student
where class_id=(
select class_id
from student
where username=‘张三’);
内部为张三所在班级id,外部为查询这个班级id的其他同学信息

5.合并查询

(1)union
(进行结果集的合并并去重)

eg:查询id<3和名字为‘英语’的课程
select * from course where id<3
union
select * from course where name=‘英语’;

(2)union all
(取得两个结果集的并集,不会去重)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值