本篇博客是看黑马培训视频的笔记,用了视频中的代码,如侵可删。
一、条件查询
首先创建一张表,并插入一些数据,SQL代码如下:
CREATE TABLE student (
id INT, -- 编号
NAME VARCHAR(20), -- 姓名
age INT, -- 年龄
sex VARCHAR(5), -- 性别
address VARCHAR(100), -- 地址
math INT, -- 数学
english INT -- 英语
);
INSERT INTO student(id,NAME,age,sex,address,math,english) VALUES
(1,'马云',55,'男','杭州',66,78),
(2,'马化腾',45,'女','深圳',98,87),
(3,'马景涛',55,'男','香港',56,77),
(4,'柳岩',20,'女','湖南',76,65),
(5,'柳青',20,'男','湖南',86,NULL),
(6,'刘德华',57,'男','香港',99,99),
(7,'马德',22,'女','香港',99,99),
(8,'德玛西亚',18,'男','南京',56,65);
SELECT * FROM student; #查看student表中所有数据
-- 查询 math 分数大于 80 分的学生
SELECT * FROM student WHERE math>80;
-- 查询 english 分数小于或等于 80 分的学生
select * from student3 where english <=80;
-- 查询 age 等于 20 岁的学生
select * from student3 where age = 20;
-- 查询 age 不等于 20 岁的学生,注:不等于有两种写法
select * from student3 where age <> 20;
select * from student3 where age != 20;
##################################################
-- 查询 age 大于 35 且性别为男的学生(两个条件同时满足)
select * from student3 where age>35 and sex='男';
-- 查询 age 大于 35 或性别为男的学生(两个条件其中一个满足)
select * from student3 where age>35 or sex='男';
-- 查询 id 是 1 或 3 或 5 的学生
select * from student3 where id=1 or id=3 or id=5;
#in 里面的每个数据都会作为一次条件,只要满足条件的就会显示
-- 查询 id 是 1 或 3 或 5 的学生
select * from student3 where id in(1,3,5);
-- 查询 id 不是1,3,5 的学生
select * from student3 where id not in(1,3,5);
#age BETWEEN 80 AND 100 相当于: age>=80 && age<=100
#查询 english 成绩大于等于 75,且小于等于 90 的学生
select * from student3 where english between 75 and 90;
一、模糊查询
LIKE 表示模糊查询,格式如下:
SELECT * FROM 表名 WHERE 字段名 LIKE '通配符字符串';
通配符:% 和_
%:可以匹配任意多个字符串
_:匹配一个字符
示例如下:
-- 查询姓马的学生
select * from student3 where name like '马%';
select * from student3 where name like '马';
-- 查询姓名中包含'德'字的学生
select * from student3 where name like '%德%';
-- 查询姓马,且姓名有两个字的学生
select * from student3 where name like '马_';