数据表准备:
CREATE TABLE student3 ( id int, name varchar(20), age int, sex varchar(5), address varchar(100), math int, english int);INSERT INTO student3(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);
sql注释:
单行注释 -- 这是单行注释 注意--后面加一个空格再写内容# 这也是单行#号注释 一般在cmd上写
多行注释/* 多行注释*/
查询语句:
1. 简单查询: select * from 表名
select * from student3 -- 查询student3所以信息select id from student3 -- 查询表中的字段 idselect id,name,sex from student3 -- 查询student3中的字段id name sex/* *代表查询所有,多个字段查询,查询的字段使用逗号隔开*/
2.where查询 where 关键字
where 关键字代表条件根据什么条件来查询*/select * from student3 where id = 1; -- 查询id为1的所有字段信息select * from student3 where name = "马云" -- 查询name等于马云的信息
3.比较运算符查询
>大于 =大于等于 =等于 <>、!=不等于
select * from student3 where math > 66 -- 查询数学成绩大于66的所有学生信息select name from student3 where english = 0 -- 查询英语成绩等于null的学生姓名
4.逻辑运算符查询
and(&&) 多个条件同时满足 or(||) 多个条件其中一个满足 not(!) 不满足
select name from student3 where math = 56 && english = 77 -- 查询数学为56 且 英语为77的学生姓名select * from student3 where sex in('女'); -- 查询性别为女的信息select * from student3 where sex not in('女') -- 查询性别不为女的信息
5.between 值1 and 值2 查询在值1和值2之间的数据 表示从值1到值2范围,包头又包尾
select * from student3 where math between 56 and 99 -- 查询数学分数在56到90之间的学生信息select * from student3 where math>=56 and math<=99 -- 等同于 上面
6.like ,模糊查询
格式:SELECT * FROM 表名 WHERE 字段名 LIKE '通配符字符串';
通配符字符串:
%: 表示0个或多个字符(任意个字符)
_: 表示一个字符
select * from student3 where name like "马%"; -- 查询所有姓马的信息select * from student3 where name like "马_"; -- 查询姓马且名字是两个字的信息
7.排序
order by 子句:可以将查询出的结果进行排序(排序只是显示方式,不会影响数据库中数据的顺序)
ASC: 升序, 默认是升序 ; DESC: 降序
select * from student3 order by id; -- 根据id升序查询 select * from student3 order by id desc -- 根据id降序查询select * from student3 order by name desc -- 根据姓名降序查询 根据首字母 排序
组合排序:
select * from student3 order by math asc,english asc -- 根据数学成绩培训,英语成绩排序
8.聚合函数查询
五个聚合函数:
count: 统计指定列记录数,记录为NULL的不统计
sum: 计算指定列的数值和,如果不是数值类型,那么计算结果为0
max: 计算指定列的最大值
min: 计算指定列的最小值
avg: 计算指定列的平均值,如果不是数值类型,那么计算结果为0
select count(*) 信马的人数 from student3 where name like "马%" -- 查询有多少个学生select sum(math) 总分数 from student3 -- 求班级总分数select m.........