MySQL学习(二)——DML和DQL语法详解

275 阅读3分钟

「这是我参与2022首次更文挑战的第3天,活动详情查看:2022首次更文挑战」。

前言

 大家好,我是程序猿小白 GW_gw,很高兴能和大家一起学习进步。

以下内容部分来自于网络,如有侵权,请联系我删除,本文仅用于学习交流,不用作任何商业用途。

摘要

 本文主要介绍Mysql中关于DML和DQL语法的介绍,较为核心。

1. DML

1.1 插入数据

建议书写的时候写上对应的列名,这样可以不按照列的顺序进行插入,如果不写默认为原始列的顺序。

【格式】

insert into 表名(列名1,列名2......) values(值1,值2......);
insert into 表名 values(值1,值2......);

1.2 删除数据

  1. 删除数据,如果没有where,则删除表中所有数据 【格式】
delete from 表名 where 条件
  1. 删除表,并创建一个新的和删除的表的结构相同的表 【格式】
truncate table 表名

1.3 修改数据

【格式】

update 表名 set 要修改的列名 where 条件
例如:
update stu set age=100 where id=1;

不加条件,所有的age都会被改为100

2. DQL

2.1 排序查询

【格式】

order by 排序字段 排序方式 
例如:
select * from stu order by age (不写则为ASC默认升序)
                               DESC 降序  
多字段排序
select * from stu order by  age DESC  name DESC
                           第一个字段相同时,按照第二个字段排序

2.2 聚合函数

  1. count 计算个数
  2. max 计算最大值
  3. min 计算最小值
  4. sum 计算和
  5. avg 计算平均值

注意:聚合函数排除了null值。

select count(name) from stu;
//解决聚合函数排除null值,null也被统计。
select count(isnull(name,0)) from stu;

//通常我们选择不包含null的列,例如:主键
select count(id) from stu;
select count(*) from stu;

【实例展示】

select min(age) from stu;
select max(age) from stu;
select sum(age) from stu;
select avg(age) from stu;

2.3 分组查询

【格式】

group by 分组字段;

【实例展示】

select sex,avg(score) from stu group by sex;
select sex,avg(score) from stu where score > 70 group by sex;
select sex,avg(score) from stu where score >70 group by sex having count(id)>20
  • where在分组之前进行限定,having在分组之后进行限定。

  • where后不可以跟聚合函数的判断,having后可以跟聚合函数。

2.4 分页查询

【格式】

limit 开始的索引,每页查询的条数

【实例展示】

//第一页显示0,1,2
select * from stu limit 0,3;
//第二页显示3,4,5
select * from stu limit 3,3;

开始索引的计算公式:

开始索引=(当前页码-1)*每页显示的条数

2.5 基础查询

【查询语法】

select 字段列表
from 表名
where 条件列表
group by 分组字段
order by 排序条件
limit 分页限定

【实例展示】

select name,age from stu;
  1. 使用 distinct关键字去重
select distinct age from stu;
  1. 计算两列之和
select math,chinese ,math+chinese from stu;
  1. 有null参与的运算结果为null,对此结果使用ifnull判断进行处理。
select math,chinese ,ifnull(math,0)+ifnull(chinese,0) from stu;
  1. 使用as关键字起别名
select math as 数学,chinese 语文 ,math+chinese from stu;

2.6 条件查询

  1. 具体条件查询where 可以使用运算符进行条件判断。
select name from stu where id=0;
                             >
                             <
                             !=
                           age>=20 and age <=30
                           age between 20 and 30       
                           age>=20 or age <=30
                           age in (20,30)

需要注意的是:

  • null不能用等号判断,应该用is,is not
select * from stu where math is null;
select * from stu where math is not null;
  1. 模糊查询like
占位符:
_ 单个任意字符
% 多个任意字符
select * from stu where name like '杨%'; 

小结

以上就是Mysql语法中较为核心的查询语法,希望对读者有所帮助,如有不正之处,欢迎留言指正。