sql数据库连表查询记录

 

1、内连接查询(查询两个表都符合条件的数据)

关键字 inner join

 基本格式  select 字段列表  from 表1 inner join 表2 on 表1.字段=表2.字段

 

 2、左连接查询(左边表中数据显示全部)

关键字 left join左边表中显示全部,右边表符合条件的显示,不符合条件的以null填充

基本格式 select 字段列表 from 表1 left join 表2 on 表1.字段=表2.字段

 

3、右连接查询(右边表中数据显示全部)

关键字 right join
右表显示全部,左表显示符合条件的
数据,不符合的以null填充
基本格式
select 字段列表
from 表1 right join 表2
on 表1.字段=表2.字段

 4、union连接

select * from a表 union select * from b表; //union连接(前提条件,多个关系表的表字段数目必须相同)

举例:存在两张表,且表字段数都是两列

 

练习题:

-- 查询一班得分在80分以上的学生

select * from student stu LEFT JOIN class cl on stu.c_id=cl.Id
where stu.Score>80 and cl.`Name`=\'一班\'

 

-- 用一条sql语句查询出各个班级的男生人数和平均分

select count(sex) as \'男生人数\',avg(Score) as \'平均分\' from student
where sex=\'男\' GROUP BY c_id


查找出name中所有相同的名字
select * from student
where Name in (SELECT name from student GROUP BY name HAVING count(name) >1)

posted @ 2023-02-03 19:49  Catonce  阅读(331)  评论(0)    收藏  举报