DQL语句用来查询表中的数据,不会修改表中的数据,只用于显示数据。
语法:select 字段1,字段2… from表名 [ where 条件表达式]
特点:
- 多个字段之间用逗号隔开,如果查询所有字段的数据,可用*代表所有字段
- 可使用where子句包含查询的条件
6.1 基础查询
- 查询学生表所有学生的信息
select * from student;
- 查询所有学生的姓名和年龄
select name,age from student;
6.2 使用别名查询
使用别名的好处:显示的时候使用新的名字,并不修改表的结构。
语法:字段名或表名 [ as ] 别名,这里的as可以省略
- 查询所有学生的姓名和年龄,使用别名
select name as 姓名,age 年龄 from student;
select st.name 姓名,age 年龄 from student;
st 表使用别名原因:在多表连接查询时,用别名来区分不同的表的同名字段
6.3 清除重复值
如果表的某个字段有多个相同的值,可以使用 distinct 关键字来去除重复值,只保留一个。
示例:select distinct address from student;
6.4 列值参与数学运算
可以让查询出的列值参与数学运算,前提是列必须是数字类型。
示例:查询的时候把学生数学和英语的成绩总和显示出来
select *,(math+english) 数学英语总成绩 from student2;
6.5 条件查询
条件查询:根据条件过滤原始表的数据,查询到想要的数据
语法:select 要查询的字段或表达式 from 表名 where 条件表达式
流程:取出表中的每条数据,满足条件的记录就返回,不满足条件的记录不返回
条件查询中可使用的运算符有2类:比较运算符、逻辑运算符
6.5.1 比较运算符

>、<、<=、>=、=、<>
需求:
- 查询math分数大于80的学生
select * from student2 where math>80;
- 查询english分数小于或等于80的学生
select * from student2 where english<=80;
- 查询age等于20岁的学生
select * from student2 where age=20;
- 查询age不等于20岁的学生。注:不等于有两种写法
select * from student2 where age !=20;
select * from student2 where age <>20;
in的用法(等值比较):
select 字段名 from表名 where字段 in (数据 1, 数据 2…);
in里面的每个数据都会作为一个匹配条件,只要字段的值等于此数据,就返回对应的数据记录。
需求:查询数学成绩为98,66和99的学生编号、姓名,数学成绩
select id,name,math from student2 where math in (98,66,99);
between and 范围查询:
between值 1 and值 2,表示从值 1 到值2的范围,包含头也包含尾
比如: age between 80 and100 相当于: age>=80 && age<=100
需求:查询英语成绩在[70,88]的学生的Id,姓名和英语成绩
select id,name,english from student2 where english between 70 and 80;
like模糊查询:
select 字段名 from 表名 where 字段 like ‘通配符字符串’
MySQL的通配符有:
| 通配符 | 说明 |
|---|---|
| % | 匹配任意个字符(0或多个) |
| _ | 匹配一个字符 |
需求:
- 查询姓名中包含“德”字的学生
select * from student2 where name like ‘%德%’;
- 查询姓马,且姓名有两个字的学生
select * from student2 where name like ‘马_’;
- 查询姓名中第2个字是德字的学生
select * from student2 where name like ‘_德%’;
IS NULL :
查询某个字段值为null的学生记录,用字段 is null来表述条件
select * from student2 where english is null
6.5.2、逻辑运算符

需求:
- 查询age大于等于35且性别为男的学生(同时满足两个条件)
select * from student2 where age >=35 && sex=’男’;
- 查询age大于等于35或性别为男的学生(两个条件满足其中一个)
select * from student2 where age >=35 || sex=’男’;
- 查询id是1或3或5的学生(两个条件满足其中一个)
select * from student2 where id=1 or id=3 or id=5;
注意:如果多个查询条件是用or连接的,并且是等值比较,就可以改造成 In(值列表)语句
select * from student2 where id in (1,3,5);
