数据库查询操作基础

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;

在这里插入图片描述
方法二:
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值