MySQL入门 之单表查询_2020-09-16

MySQL入门 之单表查询

前言

上一期介绍了mysql数据库的创建以及简单的增删改查 相信大家已经对mysql有一个简单的了解了 今天来说一下单表的相关操作

2.1 排序

排序是单表中常见的操作 会有这样几个关键词

-- order  by 排序关键字

-- asc 升序     desc 降序

语法:select * from 表名 order by 排序列 asc | desc


例题

-- 1.使用价格排序(降序)

select * from product order by price desc;

-- 2.在价格排序(降序)的基础上,以分类排序(降序)

select * from product order by price desc, category_id desc;

-- 3.显示商品的价格(去重复),并排序(降序)

select distinct price from product order by price desc;

2.2 聚合

  • 聚合函数 :SQL基本函数,聚合函数对一组值的执行计算,并返回单个值,也被称为组函数。
  • 常见的聚合函数:
    除count以外, 聚合函数忽略空值 ,如果count 函数的应用对象是一个确实列名,并且该列存在空值,此时COUNT仍会忽略空值。
-- 统计个数: count

-- 最大值: max

--最小值: min

--求和: sum

-- 平均值: avg




-- 例题  

--  聚合函数

-- 1 统计个数

-- count(列名 | * | 数字)
select count(category_id) from product;	  # 结果:12,忽略了空值
select count(*) from product;		  # 结果:13
select count(1) from product;		  # 结果:13

-- 2 价格最大值

select max(price) from product;

-- 3 价格最小值

select min(price) from product;

-- 4 价格求和

select sum(price) from product;

-- 5 价格平均值

select avg(price) from product;

2.3 分组

group by的含义:
将查询结果按照1个或多个字段进行分组,字段值相同的为一组

group by可用于单个字段分组,也可用于多个字段分组

select 分组列 | 聚合函数 from 表名 group by 分组列 having分组条件;

-- 
-- 分组
-- #1 统计各个分类商品的个数
select category_id , count(1) from product group by category_id

-- #2 统计各个分类商品的个数,且只显示个数大于1的信息
select category_id , count(1) from product group by category_id having count(1) > 1

select category_id , count(1) as c from product group by category_id having c > 1

2.4 分页

limit 开始索引, 每页显示个数
-----开始索引  ,从0 开始。
----- 第一页 , 每页三条
select * from  product limit 0,4;

-- 第二页,每页3条

select * from product limit 3,3;

-- 第三页,每页3条

select * from product limit 6,3;

-- 第pageNum页,每页pageSize条

select * from product limit (pageNum - 1) *  起始索引 , 页面尺寸;

猜你喜欢

转载自blog.csdn.net/LiGuanLink/article/details/108622488