前言
数据库名称可以为【schoolDB】,字符集【utf8】,排列顺序【utf8_general_ci】。
1.建表语句——DDL
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '学号',
`createDate` datetime DEFAULT NULL COMMENT '创建时间',
`userName` varchar(20) DEFAULT NULL COMMENT '用户名',
`pwd` varchar(36) DEFAULT NULL COMMENT '密码',
`phone` varchar(11) DEFAULT NULL COMMENT '手机号',
`age` tinyint(3) DEFAULT NULL COMMENT '年龄',
`sex` char(2) DEFAULT NULL COMMENT '性别',
`introduce` varchar(255) DEFAULT NULL COMMENT '简介',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
2.插入语句——DML
insert into student values(0,'2024-3-25 13:25:00','时代少年团','123456',
'18532080258','18','男','时代少年团我们喜欢你!');
insert into student values(0,'2024-3-25 13:25:00','宋亚轩','123456',
'18565482158','18','男','666');
insert into student values(0,'2024-3-25 13:25:00','丁程鑫','123456',
'18565482468','18','男','999');
insert into student values(0,'2024-3-25 13:25:00','马嘉祺','123456',
'18565482189','18','男','骑是马加奇');
insert into student values(0,'2024-3-25 13:25:00','刘耀文','123456',
'18565484868','18','男','是个有一点狠的崽子');
insert into student (userName,age,introduce) values('coke',18,'诱惑力的睫毛,甜如蜜的嘴角,co老师是一个拥有骚刚的性感小野猫')
3.基础查询语句——DQL
# 1.基础查询
select*from student;
# 2.分列匿名以及筛选数据查询
select userName as '姓名',age 年龄,sex '性别',introduce'简介'
from student
where pwd is not null;
# 3.去重查询
select distinct sex '性别类型'from student;
# 4.排序查询
select userName as '姓名',age 年龄,sex '性别',introduce'简介' from student order by age desc;
# 5.分页查询·limit这是个重载函数,
# 1个参数的limit用法是显示多少条信息
select*from student limit 2;
# 2个参数,参数1:从第N条开始查询,N的起始坐标为0条。参数2:查询条数
select*from student limit 4,2;
4.查询语句——DQL
SELECT * FROM `student` where userName like '马%';
SELECT * FROM `student` where userName like '刘%';
SELECT * FROM `student` where userName like 'cok_';
SELECT * FROM `student` where pwd is null;
SELECT * FROM `student` where pwd is not null;
SELECT * FROM `student` where age between 10 and 20;
SELECT * FROM `student` where createDate between '2024-03-26 00:00:00' and '2024-03-29 00:00:00';
SELECT * FROM `student` where userName in('coke','马嘉祺');
5.聚合函数
#五个常用的聚合函数
select count(*) from student where pwd is not null;
select max(age) '最大年龄',min(age)'最小年龄' from student;
select avg(age) '平均年龄' from student;
select sum(age) '总年龄' from student;
select avg(age) '平均年龄',sum(age)/(select count(*) from student)'sum计算平均年龄' from student;
select studentId,
count(studentId)'学生考试科目数量',
sum(score)'学生总成绩',avg(score)'学生的平均分'
from result GROUP BY studentId;
SELECT userName,testName,score from result,student
where result.studentId=student.id;
select userName,
count(score)'参与考试数量',
avg(score)'每人平均分数',
sum(score)'每人的总分'
from result,student
where result.studentId=student.id
and score>60
GROUP BY userName;