欢迎访问 夜阑小雨 我的学习碎片档案,这里记录了我的学习内容和工作中经验,希望给您带去帮助。

Mysql 多表查询

phonegap开发 夜阑小雨 1648℃ 0评论

MYSQL
1、多表查询
超过一个表的综合查询;
注意:找到表与表之间的纽带(桥梁)
分类:
1:内连接:
等值连接:查询的结果带有重复记录的
自然连接:查询结果中没有重复的记录
(distinct|group by)删掉重复记录的查询
2:外连接:
左连接:
右连接
全连接
3:交叉连接:
student_info  学生信息表
s_id s_name  age  area
1  Tom  20  北京
2  Jack  21  上海
3  Lily  19  南京
4  Damat  22  北京
5  DaiJun  22  上海

1,2,3
marks 成绩表:
s_id c_id mark
1  1  60
2  2  70
3  1  80
4  3  60
1  2  70
2  3  59
class 科目表
c_id c_name
1  语文
2  数学
3  英语
1)等值连接:
select 字段列表 from 表列表 where 表1.字段1=表2.字段1 and 表2.字段2=表3.字段2 and。。。。。。
eg:检索出所有的学生信息及其各科目所考试的成绩
编号,姓名,年龄 地区 科目和成绩;

select s_id,s_name,age,area,c_name,marks
from student_info,marks,class
where student_info.s_id=marks.s_id
and marks.c_id=class.c_id;
注意:如果查询涉及到的字段中,在多个表中存在,那么要使用"表名.字段名"的方式来表明是那个表中的;
2)如果重复的字段较多,那么我们给使用的表起个别名:
表名 as 别名|表名 别名

select s.s_id,s_name,age,area,c_name,marks
from student_info as s,marks as m,class as c
where s.s_id=m.s_id
and m.c_id=c.c_id;
eg:查询出各科目的平均成绩?group by
select c_name,avg(marks) as "jjj"
from class,marks
where class.c_id=marks.c_id;
group by c_name;
eg:统计学生所在地的学生人数?
eg:统计学生大于70的所在地的学生人数
3)sql语句中中:
内连接:
select 字段列表 from 表1 innerjoin 表2
on 表1.字段1=表2.字段1
eg:
检索出所有学生的姓名和成绩;
select s_name,marks from student_info s inner join marks m on s.s_id=m.s_id
外连接:
左连接:
格式:
select 字段列表 from 表1 left outerjoin 表2
on 表1.字段1=表2.字段1 
注意:以左边的表为参照物,用右边的表进行匹配,如果右边的表中有匹配记录,那么就显示记录,如果没有匹配的记录,那么就填充null;

eg:
打印出学生的全部成绩?

右连接:
格式:
select 字段列表 from 表1 right outerjoin 表2
on 表1.字段1=表2.字段1 
注意:以右边的表为参照物,用左边的表进行匹配,如果左边的表中有匹配记录,那么就显示记录,如果没有匹配的记录,那么就填充null;
全连接:在mysql中部支持全连接
格式:
select 字段列表 from 表1 left outerjoin 表2
on 表1.字段1=表2.字段1

union all

select 字段列表 from 表1 right outerjoin 表2
on 表1.字段1=表2.字段1
union all:将查询得到得两个记录集合并起来,但是不去除重复的记录;默认使用的情况下没有all—就相当于加了distinct去掉的重复的记录;现在所实现的效果才是全连接的效果;
4)交叉连接:
cross
格式:
select 字段列表 from 表1 cross 表2
供应商  超市
1  1
2  2
3  3
5)自连接:
inner join

person

p_id  p_name  s_id
1 tom  2
2  lily  3
3  damat  4
4  mack

职工  领导  经理
tom  领导  lily
lily  领导  damat
damat 领导  mack
per 职工表
p_id  p_name  s_id
1 tom  2
2  lily  3
3  damat  4
4  mack

cap 经理表
p_id  p_name
1 tom 
2  lily 
3  damat
4  mack

select per.p_name,"领导",cap.p_name
from person per,person cap
where per.s_id=cap.p_id;

6)sql语句中的常量:
select "字符" from 表
7)成绩大于60的学生姓名:
select s_name from student_info,marks
where student_info.s_id=marks.s_id marks>60;

转载请注明:夜阑小雨 » Mysql 多表查询

喜欢 (0)or分享 (0)
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
(3)个小伙伴在吐槽
  1. 反反复复
    夜阑小雨2021-07-09 10:55 回复
  2. 嘎嘎嘎
    夜阑小雨2021-07-09 10:53 回复
  3. mysql订单
    夜阑小雨2021-07-09 10:50 回复