目录

1.使用环境

2.条件判断

2.1.case when

2.2.if

3.窗口函数

3.1.排序函数

3.2.聚合函数

3.3.partiton by

​​​​​​​3.4.order by

4.待续


1.使用环境

数据库:MySQL 8.0.30

客户端:Navicat 15.0.12

2.条件判断

2.1.case when

语法格式:

case when [condition] then [result1]...else [default] end

如果condition条件成立,返回result1,否则返回default,以end结束条件判断。

建表:

CREATE TABLE t_1 (
 id int(10) NOT NULL,
 name varchar(255) DEFAULT NULL,
 age int(5) DEFAULT NULL,
 score int(5) DEFAULT NULL,
 PRIMARY KEY (`id`)
);

> OK

> 时间: 0.008s

添加数据:

INSERT INTO t_1 VALUES
('1', '张三', '20', '68'),
('2', '李四', '19', '97'),
('3', '王五', '21', '55'),
('4', '赵六', '22', '81');

> Affected rows: 4

> 时间: 0.001s

为t_1添加一列level,表示学生的得分等级

select * ,
  case 
  	when t_1.score >= 80 then '优秀'
    when t_1.score < 80 and t_1.score >= 60 then '一般'
    else '不及格'
  end as level
from t_1;

MySQL进阶一-LMLPHP

2.2.if

语法格式:

if(condition,result1,result2)

如果condition条件为真,则返回result1否则返回result2。

为t_1添加一列,表示学生是否成年:

select *,
if(t_1.age >= 18,'成年人','未成年人') as 是否成年
from t_1;

MySQL进阶一-LMLPHP

3.窗口函数

语法格式:

窗口函数 over(partiton by 分组字段 order by 排序字段 asc|desc)

​​​​​​​3.1.排序函数

  • rank()
  • dense_rank()  
  • row_number()

​​​​​​​3.2.聚合函数

  • sum(字段) ---求和
  • count(字段) ---统计个数
  • max(字段) ---最大值
  • min(字段) ---最小值
  • avg(字段) --平均值

​​​​​​​3.3.partiton by

将表数据根据partiton by后面的字段进行分组。

partiton by和 group by分组的区别:

  • group by会改变显示结果的行数(相当于按照字段折叠,把同一组的数据折叠在一起)。
  • partiton by不会改变表显示的行数(与原表显示一样),只是把相同组的数据归纳纵向相连在一起。

​​​​​​​3.4.order by

根据指定的字段进行排序。

4.待续

进阶二补上了:

MySQL进阶二-CSDN博客文章浏览阅读250次。MySQL进阶操作二。MySQL进阶一-LMLPHPhttps://blog.csdn.net/ak2111/article/details/137711598?spm=1001.2014.3001.5501

04-13 16:44