mysql的查询--子查询,order by,group by,having

2023-05-13,,

一、
1.多表查询
格式1:
select 字段列表
from 表1 join 表2 on 表1.字段1=表2.字段1
where 查询条件

格式2:
select 字段列表
from 表1 join 表2 on 表1.字段1=表2.字段1
join 表3 on 表2.字段2=表3.字段2
where 查询条件

格式3:
select 字段列表
from 表1,表2
where 表1.字段1=表2.字段1 and 查询条件

二、子查询
说明:在查询条件中,可以使用另一个查询的结果作为条件的一部分;另一个查询的结果就是子查询。

格式:
select 字段列表
from 表1
where 字段 in/exist/比较运算符 (子查询)

参数说明:in(用于进行一个给定值是否在子查询结果集中的判断)
any/some:比较时,只要有满足条件的即可。
all:比较时,必须所有都满足条件。
exists:用于测试子查询的结果是否为空表,若不为空返回True。

例如:exists

select * from sell as a where exists(
select * from book as b where b.图书编号 = a.图书编号 and 图书类别="网页设计");

三、准备工作
1.获取到.sql源码
2.打开mysql的 workbench 窗口;登陆密码admin@user
3.复制源码的所有代码,粘贴到mysql窗口的查询中,并运行 (即可得到数据库)
4.刷新数据库列表,并在数据库名上双击 (目的:让数据库为当前数据库)

操作1:查找订购册数为7的图书信息
分析:用到两个表sell,book;共有的字段是图书编号;最后要的结果是图书信息;而条件是订购表的信息;
方法1:多表查询
select book.*
from sell join book on sell.图书编号 = book.图书编号
where sell.订购册数=7;

方法2:子查询

select * from book
where 图书编号 in (select 图书编号 from sell where 订购册数=7);

操作2:查找购买了除“网页程序设计”以外图书的会员信息
方法1:
步骤1:找到图书表中除“网页程序设计”外的图书编号

步骤2:通过找到的图书编号,在sell表中查找身份证号

步骤3:通过找到的身份证号,查找会员表的会员信息。

-- 步骤1:
select 图书编号 from book where 书名="网页程序设计";
-- 步骤2
select distinct 身份证号 from sell where 图书编号 not in(
select 图书编号 from book where 书名="网页程序设计");
-- 步骤3
select * from members where 身份证号 in(
select distinct 身份证号 from sell where 图书编号 not in(
select 图书编号 from book where 书名="网页程序设计"));

操作3:查询book表中所有比“网页设计”类图书价格都高的图书基本信息。

-- 步骤1:找到网页设计类图书的所有价格

-- 步骤2:找出比较以上价格都高的图书信息
select * from book where 单价>all(
select 单价 from book where 图书类别="网页设计");
-- 等价于
select * from book where 单价>(
select max(单价) from book where 图书类别="网页设计");

select * from book where 单价>any(
select 单价 from book where 图书类别="网页设计");
-- 等价于
select * from book where 单价>(
select min(单价) from book where 图书类别="网页设计");

练习:查询所有比会员“李华”订购的图书单价都高的订购信息。

select * from sell where 订购单价>all(
select 订购单价 from sell where 身份证号 in (
select 身份证号 from members where 会员姓名="李华"));

四、分类汇总和排序
1.分类汇总:按某列进行分类,并对每一类进行统计。
select
from
where
group by 列名 having 分组条件

例如:统计男生的人数;再统计女生的人数;

例如:统计不同性别的人数;

执行顺序:from----where----group by----having-----select---order by---limit

2.having条件:必须跟在group by后,是对分组结果的筛选。

3.order by 字段名 asc/desc:对查询结果进行排序。

4.limit n: 筛选前n个结果返回
limit m,n :筛选从第m个往后的n个

-- 1、limit关键字
select * from sell;

select * from sell limit 3;

select * from sell limit 3,4;

-- 2、order by关键字
select * from sell order by 身份证号;

select * from sell order by 身份证号,订购单价 desc;

-- 3、group by 关键字
-- 统计计算机类图书的单价平均值
select avg(单价) as 单价平均值 from book where 图书类别="计算机";

select avg(单价) as 单价平均值 from book where 图书类别="网页设计";
-- 统计每类图书的单价平均值
select 图书类别,avg(单价) as 单价平均值 from book group by 图书类别;

-- 统计每类图书的单价平均值 ,找出平均单价大于27的信息;
select 图书类别,avg(单价) as 单价平均值 from book group by 图书类别 having 单价平均值>27;

日行一善:

今天看到几个学校的学生在教学楼楼道抽烟(关键还有一个女生,虽然动作很帅),但这是公共场所。我就友情提醒,他们要到洗手间抽烟。娃们很礼貌的就去了。

日进一步:

今天上午的课,手机没有怎么玩,看了一会爬虫的书。

mysql的查询--子查询,order by,group by,having的相关教程结束。

《mysql的查询--子查询,order by,group by,having.doc》

下载本文的Word格式文档,以方便收藏与打印。