mysql 查询

合并结果集(联合查询)

合并结果集就是将多个查询结果,纵向拼接在一起。

语法

select * from tb_a
union
select * from tb_b
--================================
select id,name,age from tb_a 
union all
select birthday,name,age from tb_b
/*
union 会将完全一致的数据去重
union all 会将所有数据保留
合并的两表的列数,数据类型要一致!!
ps: 一般用在将一个大表拆成两个表是,这两张表的拼接使用
*/

连接查询

连接查询是将多个表的查询结果,横向拼接后展现

 内连接

语法:
select * from tb1 inner join tb2 on tb1.字段 = tb2.字段; 

外连接

外连接分左外连接和右外连接.

语法:

select * from tb1 left outer join tb2 on tb1.字段 = tb2.字段

-- 查询学生信息,如果有班级信息就查询班级信息

select * from stu left outer join class on stu.cid = class.cid;
select * from stu left join class on stu.cid = class.cid;
select * from stu right outer join class on stu.cid = class.cid;

子查询(subquery)

子查询其实就是嵌套查询

子查询嵌套,

可以嵌套在where后面当条件,

可以嵌套在from后面当表

-- 查询与张三同一个班级的学生。(子查询当条件)
-- 1) 先找到张三所在班级
select cid from stu where sname = '张三'
-- 2) 找到1班所有人
select * from stu where cid = 1
-- 改造成:子查询
select * from stu where cid = 
(select cid from stu where sname = '张三')

-- =======================================================================

/*
子查询当条件时需要注意返回的结果的个数
如果是一个返回值,条件可以使用=,>,<,等等
如果是多个返回值,条件用in
*/
select * from stu where cid in 
(select cid from stu where age = 45)

-- =======================================================================

-- 成绩高于3号班级所有人的学生信息
-- 1) 查询3班最高分
select max(score) from stu where cid = 3;
-- 2) 大于最高分
select * from stu where score > 96;
-- 改造
select * from stu where score > 
(select max(score) from stu where cid = 3)

-- =======================================================================

-- 有2个以上直接组员的学生信息
-- 2个以上组员的组长编号,组内人数
select groupLeaderId,count(sid) from stu group by groupLeaderId having count(sid) > 2
-- 查询组长信息
select * from stu where sid in (1007,1010)
-- 改造
select * from stu where sid in 
(select groupLeaderId from stu group by groupLeaderId having count(sid) > 2)

-- =======================================================================

-- 变式写法:子查询当表
select * from stu s,(select groupLeaderId,count(sid) from stu group by groupLeaderId having count(sid) > 2) z 
where s.sid= z.groupLeaderId

-- =======================================================================

-- 求1008学生编号、姓名、组长编号和组长姓名
select s.sid,s.sname,s.groupLeaderId,z.sname from stu s,stu z where s.groupLeaderId = z.sid and s.sid =1008

-- =======================================================================

-- 查询每个学生成绩大于等于60且成绩总和大于200的班级编号以及成绩和并根据成绩和升序
select sum(score),cid from stu group by cid having min(score) >=60 and sum(score) > 200 order by sum(score);

-- =======================================================================

-- 自连接
-- 查询学生信息以及对应的组长信息
select * from stu s,stu z where s.groupLeaderId = z.sid

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值