四、MySQL关键字查询
4.1 运算符
比较运算符:
逻辑运算符:
注意事项
- WHERE条件可以使用表达式,但不能使用别名。
- AND的优先级高于OR,在同时使用时,需要使用小括号()包裹优先执行的部分
4.2 案例代码
4.2.1 基本查询 WHERE
-- 查询英语不及格的同学及英语成绩 ( < 60 )
select name,english from exam_result where english < 60;
-- 查询语文成绩好于英语成绩的同学
select name,chinese,english from exam_result where chinese > english;
-- 查询总分在 200 分以下的同学
select name from exam_result where chinese + math + english < 200;
4.2.2 AND 与 OR 查询
-- 查询语文成绩大于80分,且英语成绩大于80分的同学
select name,chinese,english from exam_result where chinese > 80 and english > 80;
-- 查询语文成绩大于80分,或英语成绩大于80分的同学
select name,chinese,english from exam_result where chinese > 80 or english > 80;
4.2.3 范围查询
-- 查询语文成绩在 [80, 90] 分的同学及语文成绩
select name,chinese from exam_result where chinese between 80 and 90;
4.2.4 IN查询
-- 查询数学成绩是 58 或者 59 或者 98 或者 99 分的同学及数学成绩
select name,math from exam_result where math in(58,59,98,99);
使用or也可以实现,这里不再赘述。
4.2.5 模糊查询LIKE
-- % 匹配任意多个(包括 0 个)字符
select name from exam_result where name like '孙%';
-- --匹配严格的一个任意字符
select name from exam_result where name like '孙_';
4.2.6 NULL的查询
-- 查询 qq_mail 已知的同学姓名
select name,qq_mail from student where qq_mail is not null;
-- 查询 qq_mail 未知的同学姓名
select name,qq_mail from student where qq_mail is null;
4.2.7 分页查询LIMIT
语法:
-- 从 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;
案例:
按id进行分页,每页三条记录
select id,name,math,english,chinese from exam_result order by id limit 3 offset 0; select id,name,math,english,chinese from exam_result order by id limit 3 offset 3; select id,name,math,english,chinese from exam_result order by id limit 3 offset 6;
五、修改 UPDATE
5.1 语法
UPDATE table_name SET column = expr [, column = expr ...] [WHERE ...] [ORDER BY ...] [LIMIT ...]
5.2 案例
-- 将孙悟空同学的数学成绩变更为 80 分
update exam_result set math = 80 where name = '孙悟空';
-- 将曹孟德同学的数学成绩变更为 60 分,语文成绩变更为 70 分
update exam_result set math = 60, chinese = 70 where name = '曹孟德';
-- 将总成绩倒数前三的 3 位同学的数学成绩加上 10 分
update exam_result set math = math + 10 order by chinese + math + english limit 3;
六、删除 DELETE
6.1 语法
DELETE FROM table_name [WHERE ...] [ORDER BY ...] [LIMIT ...]
6.2 案例代码
-- 删除孙悟空同学的考试成绩
delete from exam_result where name = '孙悟空';
-- 删除整张表数据
delete from exam_result;