存在两张表
1、内连接查询(查询两个表都符合条件的数据)关键字 inner join基本格式
select 字段列表
from 表1 inner join 表2on 表1.字段=表2.字段查询结果如下:
2、左连接查询(左边表中数据显⽰全部)关键字 left join
左边表中显⽰全部,右边表符合条件的显⽰,不符合条件的以null填充基本格式
select 字段列表
from 表1 left join 表2on 表1.字段=表2.字段
查询结果如下:
3、右连接查询(右边表中数据显⽰全部)关键字 right join
右表显⽰全部,左表显⽰符合条件的数据,不符合的以null填充基本格式
select 字段列表
from 表1 right join 表2on 表1.字段=表2.字段查询结果如下:
4、union连接
select * from a表 union select * from b表; //union连接(前提条件,多个关系表的表字段数⽬必须相同)举例:存在两张表,且表字段数都是两列
⽤union查询结果如下:
练习题:
-- 查询⼀班得分在80分以上的学⽣
select * from student stu LEFT JOIN class cl on stu.c_id=cl.Idwhere stu.Score>80 and cl.`Name`='⼀班'
-- ⽤⼀条sql语句查询出各个班级的男⽣⼈数和平均分
select count(sex) as '男⽣⼈数',avg(Score) as '平均分' from studentwhere sex='男' GROUP BY c_id
查找出name中所有相同的名字select * from student
where Name in (SELECT name from student GROUP BY name HAVING count(name) >1)
因篇幅问题不能全部显示,请点此查看更多更全内容