07. where条件查询
2024年10月28日大约 3 分钟
07. where条件查询
目标
- 能够写出模糊查询的SQL语句
数据准备
-- 数据准备-创建数据库表 drop table if exists students; create table students ( studentNo varchar(10) primary key, name varchar(10), sex varchar(1), hometown varchar(20), age tinyint(4), class varchar(10), card varchar(20) ); -- 数据准备-插入数据 insert into students values ('001', '王昭君', '女', '北京', '20', '1班', '340322199001247654'), ('002', '诸葛亮', '男', '上海', '18', '2班', '340322199002242354'), ('003', '张飞', '男', '南京', '24', '3班', '340322199003247654'), ('004', '白起', '男', '安徽', '22', '4班', '340322199005247654'), ('005', '大乔', '女', '天津', '19', '3班', '340322199004247654'), ('006', '孙尚香', '女', '河北', '18', '1班', '340322199006247654'), ('007', '百里玄策', '男', '山西', '20', '2班', '340322199007247654'), ('008', '小乔', '女', '河南', '15', '3班', null), ('009', '百里守约', '男', '湖南', '21', '1班', ''), ('010', '妲己', '女', '广东', '26', '2班', '340322199607247654'), ('011', '李白', '男', '北京', '30', '4班', '340322199005267754'), ('012', '孙膑', '男', '新疆', '26', '3班', '340322199000297655');
1. where条件查询的介绍
使用where条件查询可以对表中的数据进行筛选,条件成立的记录会出现在结果集中。
where语句支持的运算符
- 比较运算符
- 逻辑运算符
- 模糊查询
- 范围查询
- 空判断
where条件查询语法格式如下
-- select * from 表名 where 条件; -- 例: select * from students where studentNo = 1;
2. 比较运算符查询
- 等于: =
- 大于: >
- 大于等于: >=
- 小于: <
- 小于等于: <=
- 不等于: != 或 <>
例1:查询学号大于3的学生
select * from students where studentNo > 3;
例2:查询学号不大于4的学生
select * from students where studentNo <= 4;
例3:查询姓名不是“小乔”的学生
select * from students where name != '小乔';
3. 逻辑运算符查询
- and
- or
- not
例1:查询年龄小于20的女同学
select * from students where age<20 and sex='女'
例2:查询女学生或'1班'的学生
select * from students where sex='女' or class='1班'
例3:查询年龄不在10岁到15岁之间的学生
select * from students where age < 10 OR age > 15;
-- 或者
select * from students where not (age >= 10 and age <= 15);
-- 查询非天津的学生
select * from students where not hometown='天津'
- 说明
- 多个条件判断想要作为一个整体,可以结合‘()’。
4. 模糊查询
- like是模糊查询关键字
- %表示任意多个任意字符
- _表示一个任意字符
例1:查询姓李的学生:
select * from students where name like '李%';
例2:查询姓李并且“名”是一个字的学生:
select * from students where name like '李_';
例3:查询姓李或叫靖的学生:
select * from students where name like '李%' or name like '%靖';
例4:查询姓名中包含‘白’的学生
select * from students where name like '%白%'
5. 范围查询
- between .. and .. 表示在一个连续的范围内查询
- in 表示在一个非连续的范围内查询
例1:查询编号为3至8的学生:
select * from students where id between 3 and 8;
例2:查询编号不是3至8的男生:
select * from students where (not id between 3 and 8) and sex='男';
例3:查询家乡是北京或上海或广东的学生
select * from students where hometown in('北京','上海','广东')
6. 空判断查询
- 判断为空使用: is null
- 判断非空使用: is not null
例1:查询没有填写身份证的学生
select * from students where card is null;
例2:查询填写了身份证的学生
select * from students where card is not null
- 注意
不能使用
where card = null 判断为空不能使用
where card != null 判断非空- null 不等于 '' 空字符串
- null 不等于 字符串 'null'
7. 小结
- 常见的比较运算符有 >, <, >=, <=, !=
- 逻辑运算符and表示多个条件同时成立则为真,or表示多个条件有一个成立则为真,not表示对条件取反
- like 和 % 结合使用表示任意多个任意字符,like 和_ 结合使用表示一个任意字符
- between、and 限制连续性范围,in限制非连续性范围
- 判断为空使用: is null
- 判断非空使用: is not null