前言
数据库名称可以为【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 '年龄',
`sew` char(2) DEFAULT NULL COMMENT '性别',
`introduce` varchar(255) DEFAULT NULL COMMENT '简介',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
2、插入语句——DML
insert into student values(0,'2024-02-25 10:00:00','刘德华','123456','15612345678',62,'男','永远的男神,爱你一万年,爱你经得起考验。');
insert into student values(0,'2024-02-25 10:00:00','刘青云','123154','15612345678',65,'男','真正的演员,好角色用心演绎。');
3、查询基础语句——DQL
#1、基础查询
select * from student;
#2、分列匿名以及筛选数据查询
select useName 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;
查询语句DQL
#like用于模糊查询
SELECT * FROM `student` where userName like '张_';
SELECT * FROM `student` where userName like '刘%';
#is null的使用not代表否定
SELECT * FROM `student` where pwd is null;
SELECT * FROM `student` where pwd is not null;
#between and 是范围查询能查询数值与时间的范围
SELECT * FROM `student` where age between 30 and 40;
SELECT * FROM `student` where createDate between '2024-02-21 00:00:00'and '2024-02-23 00:00:00';
# in相当于多于or来使用
SELECT * FROM `student` where userName in ('张翰','刘德华','刘亦菲')
聚合函数
#5个常用的聚合函数count(x)min(x)最大值最小值avg(x)求平均数,sum(x)求和
#计数
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