where条件查询
例子:-- 查询数学成绩大于80分的 同学的个人信息及数学成绩
select id,name,math from exam_result where math>80;
例:–查询数学成绩大于80分的 同学的个人信息及数学成绩, 然后根据数学成绩升序排序
select id,name,math from exam_result where math>80 order by math ;
例: – 查询数学成绩等于98分的同学及个人信息
select id,name,math from exam_result where math=98;
查询存在NULL的数据
注意NULL: 用=时 不安全 ,对于NULL 查不到
解决问题:使用 <=> 这个运算符
select id,name,math from exam_result where math<=>NULL;
不等于运算符
方法一: !=
select id,name,math from exam_result where math != 98;
方法二: <>
select id,name,math from exam_result where math <> 98;
两者之间:
方法一:BETWEEN a0 AND a1
例:-- 查询数学成绩70-90之间的同学及成绩
select id,name,math from exam_result where math between 70 and 90;
方法二:
select id,name,math from exam_result where math >= 70 and math<=90;
或
例:-- 查询数学成绩在98,85,73 中的 所有同学的数学成绩和个 人信息
方法一:in
select id,name,math from exam_result where math in(98,73,85);
math in(98,73,85) 代表的是:只要数学成绩属于其中 的某一个就进行查询。
方法二:or
select id,name,math from exam_result where math =98 or math = 73 or math=85;
为NULL
select id,name,math from exam_result where math is NULL;
不为NULL
select id,name,math from exam_result where math is NOT NULL;
模糊匹配:LIKE
模糊匹配: %
例子:查找名字当中包含“三”的学生的信息
select * from exam_result where name like '% 三%';
select * from exam_result where name like '% 三'; -- 代表:一定是以三这个结尾的
select * from exam_result where name like '三%'; -- 代表:一定是以三这个字开始的
%代表的就是一个通配符
模糊匹配:_
select * from exam_result where name like'孙_';
找到以孙开头的名字,但是记住一个下划线对应一个模糊匹 配的字。
使用两个_这个只会找到以孙开头的且有3个字的 后两个字是模糊匹配的。
NOT
not是与其他结合使用的
select id,name,math from exam_result where math not in(98,73,85);
分页查询Limit
为什么要分页?
答:主要是有时候,数据量太大了,那么一次性查找数据的时候,系统会执行SQL语句,此时查询是需要时间的。有可能系统就会被卡住。所以一般优化方案就是用分页查询
原理:
每次只查询当前页需要显示的数据即可。如果每页十页数据,那么只查询10条数据。每次下一页的时候,又去请求查询10条数据.这样效率就提高了。
– 起始下标为 0
– 从 0 开始,筛选 n 条结果
SELECT ... FROM table_name [WHERE ...] [ORDER BY ...] LIMIT n;
– 从 s 开始,筛选 n 条结果
SELECT ... FROM table_name [WHERE ...] [ORDER BY ...] LIMIT s, n;
– 从 s 开始,筛选 n 条结果,比第二种用法更明确,建议使用
SELECT ... FROM table_name [WHERE ...] [ORDER BY ...] LIMIT n OFFSET s;
select * from exam_result limit s,n; 从偏移位置 为s的地方,取出n条数据。
如果没有写S,呢么默认是从0偏移开始取n个。
例:按 id 进行分页,每页 3 条记录,分别显示 第 1、2、3 页
– 第 1 页
SELECT id, name, math, english, chinese FROM exam_result ORDER BY id LIMIT 3 OFFSET 0;
– 第 2 页
SELECT id, name, math, english, chinese FROM exam_result ORDER BY id LIMIT 3 OFFSET 3;
– 第 3 页,如果结果不足 3 个,不会有影响
SELECT id, name, math, english, chinese FROM exam_result ORDER BY id LIMIT 3 OFFSET 6;
方法二: