建表到查询,mysql数据库的干货分享

数据库

一、定义

数据库(databse):数据仓库,它是保存和管理数据的仓库

如果希望在程序中实现数据持久化操作,数据库就是一种非常好的解决方案

BATCMD :百度、阿里、腾讯、携程、美团、滴滴

IOE :IBM小型机 / Oracle数据库 / EMC存储设备 - 贵

x86服务器 / MySQL / DFS : 去IOE运动 - 性价比非常高

1、分类
  • 关系型数据库(SQL)

    • 理论基础:关系代数 + 集合论
    • 具体表象:用二维表保存数据
      • 行:记录
      • 列:字段(属性)
    • 编程语言:结构化查询语言(Structured Query Language)
      • DDL(数据定义语言):create、drop、alter
      • DML(数据操作语言):insert 、delete、update
      • DQL():
      • DCL
  • 非关系型数据库(NoSQL)

  • 包含了前两种数据库的特点(NewSQL)

2、关系型数据库的产品
  • Oracle
  • MySQL:超过五百万查询性能会急剧下降,单表65535TB
  • PostgreSQL
  • SQL Server
  • DB2
  • SQLite
二、使用MySQL
1、安装
2、启动
  • systemctl start mysqld
  • systemctl status mysqld
  • systemctl stop mysqld
3、使用客服端工具连接MySQL服务器
  • mysql -u root -p
  • mysql >修改密码:alter user ‘root’@localhost identified by ‘新密码’;
  • 修改root账号,允许远程连接
    • use mysql;
    • update user set host=’%’ where user=‘root’;
    • flush privileges
  • MySQL命令:
    • 查看表:
      • show tables;
      • show columns from 表名;
      • describe 表名;
    • 查看所有数据库:show databases
    • 寻求帮助信息:? data types;(查询数据类型)
  • 在一句话结束之后,必须是;结尾
  • 退出:quit或者exit
4、SQL语言:不区分大小写

(1)与数据库相关

  • 创建数据库:create database 数据库名 default charset utf8mb4;
  • 删除数据库:drop database if exists 数据库名 ;
  • 切换数据库:use 数据库名;

(2)与二维表相关

  • 创建二维表

    • 查看创建表的语句:show create table tb_student;

    • 例如:

      create table tb_student(

      ​ stuid int not null,

      ​ stuname varchar(20) not null,

      ​ stusex char(1) default 1,

      ​ stubirth date,

      ​ stuaddr varchar(100),

      ​ primary key (stuid)

      );

    • 主键(primary key)列:能够唯一确定一条记录的列

    • 非空约束:not null

    • 默认值约束:default

    • 自动增加数值的大小:auto_increment

    • 设置独一无二,不允许重复,一张表格只有一个,在创建表格的时候设置

      • 列名 类型 其他约束 unique
      • primary key (列名)
  • 描述二维表:desc tb_student;

  • 修改二维表:

    • 添加列:alter table tb_student add column stutel char(11) not null;
    • 删除列:alter table tb_student drop column stutel;
    • 修改列:
      • alter table 表名 change column 列名1 列名2 … 数据类型 附加条件;
      • 列名没变可省略:alter table 表名 modify column 列名 数据类型;
  • 删除表相关:删除和更新一定会带上条件,几乎不会用到删除或更新全表操作!!!

    • 删除二维表:drop table if exists 列表名;
    • 删除全表内容
      • delete from 表名:自动编号不会重新编号
      • truncate table 表名:截断表,自动编号会重新编号,不要轻易执行
    • 按照条件删除:=表示相等
      • delete from 表名 where 条件
  • 添加外键(两张表建立关系,必须是具有唯一性的)

    • 一对多

      • 建表的时候添加:create table 表名(


        foregin key (列名) references 被对应的表名 (列名)

        )

      • 建表之后添加:
        alter table 表名 add constraint 外键名字 foreign key (列名)
        references 被对应的表名 (列名);

        -- 创建学院表
        create table tb_college
        (
        collid 		int auto_increment comment '编号',
        collname 	varchar(50) not null comment '名称',
        collintro 	varchar(500) default '' comment '介绍',
        primary key (collid)
        );
        
        -- 创建学生表
        create table tb_student
        (
        stuid 		int not null comment '学号',
        stuname 	varchar(20) not null comment '姓名',
        stusex 		boolean default 1 comment '性别',
        stubirth 	date not null comment '出生日期',
        stuaddr 	varchar(255) default '' comment '籍贯',
        collid 		int not null comment '所属学院',
        primary key (stuid),
        foreign key (collid) references tb_college (collid)
        );
        
    • 多对多

      -- 创建课程表
      create table tb_course
      (
      couid 		int not null comment '编号',
      couname 	varchar(50) not null comment '名称',
      coucredit 	int not null comment '学分',
      teaid 		int not null comment '授课老师',
      primary key (couid),
      foreign key (teaid) references tb_teacher (teaid)
      );
      
      -- 创建选课记录表
      create table tb_record
      (
      recid 		int auto_increment comment '选课记录编号',
      sid 		int not null comment '选课学生',
      cid 		int not null comment '所选课程',
      seldate 	datetime default now() comment '选课时间日期',
      score 		decimal(4,1) comment '考试成绩',
      primary key (recid),
      foreign key (sid) references tb_student (stuid),
      foreign key (cid) references tb_course (couid),
      unique (sid, cid)
      );
      
      
  • 插入数据

    • insert into 表名 (列名元组) values (内容元组)
  • 函数:查询函数,在终端输入 ?function

    • now(),现在时间
    • curdate():现在时间
    • datediff():计算两个日期之间相差的天数
    • floor():向下取整,不超过指定数值的最大整数
  • ER图(Entity-RelationShip Diagram)—> 设计关系型数据库的二维表

    • 矩形框:实体(表)
    • 椭圆框:实体的属性(字段、列)
    • 菱形框:实体之间的关系(连接两个实体)
5、数据查询

举例说明mysql中查询语句的使用方法

-- 如果存在名为school的数据库就删除它
drop database if exists school;

-- 创建名为school的数据库并设置默认的字符集和排序方式(collate utf8_bin)
create database school default charset utf8mb4;

-- 切换到school数据库上下文环境
use school;

-- 创建学院表
create table tb_college
(
collid 		int auto_increment comment '编号',
collname 	varchar(50) not null comment '名称',
collintro 	varchar(500) default '' comment '介绍',
primary key (collid)
);

-- 创建学生表
create table tb_student
(
stuid 		int not null comment '学号',
stuname 	varchar(20) not null comment '姓名',
stusex 		boolean default 1 comment '性别',
stubirth 	date not null comment '出生日期',
stuaddr 	varchar(255) default '' comment '籍贯',
collid 		int not null comment '所属学院',
primary key (stuid),
foreign key (collid) references tb_college (collid)
);

-- 创建教师表
create table tb_teacher
(
teaid 		int not null comment '工号',
teaname 	varchar(20) not null comment '姓名',
teatitle 	varchar(10) default '讲师' comment '职称',
collid 		int not null comment '所属学院',
primary key (teaid),
foreign key (collid) references tb_college (collid)
);

-- 创建课程表
create table tb_course
(
couid 		int not null comment '编号',
couname 	varchar(50) not null comment '名称',
coucredit 	int not null comment '学分',
teaid 		int not null comment '授课老师',
primary key (couid),
foreign key (teaid) references tb_teacher (teaid)
);

-- 创建选课记录表
create table tb_record
(
recid 		int auto_increment comment '选课记录编号',
sid 		int not null comment '选课学生',
cid 		int not null comment '所选课程',
seldate 	datetime default now() comment '选课时间日期',
score 		decimal(4,1) comment '考试成绩',
primary key (recid),
foreign key (sid) references tb_student (stuid),
foreign key (cid) references tb_course (couid),
unique (sid, cid)
);

-- 插入学院数据
insert into tb_college (collname, collintro) values 
('计算机学院', '计算机学院1958年设立计算机专业,1981年建立计算机科学系,1998年设立计算机学院,2005年5月,为了进一步整合教学和科研资源,学校决定,计算机学院和软件学院行政班子合并统一运作、实行教学和学生管理独立运行的模式。 学院下设三个系:计算机科学与技术系、物联网工程系、计算金融系;两个研究所:图象图形研究所、网络空间安全研究院(2015年成立);三个教学实验中心:计算机基础教学实验中心、IBM技术中心和计算机专业实验中心。'),
('外国语学院', '外国语学院设有7个教学单位,6个文理兼收的本科专业;拥有1个一级学科博士授予点,3个二级学科博士授予点,5个一级学科硕士学位授权点,5个二级学科硕士学位授权点,5个硕士专业授权领域,同时还有2个硕士专业学位(MTI)专业;有教职员工210余人,其中教授、副教授80余人,教师中获得中国国内外名校博士学位和正在职攻读博士学位的教师比例占专任教师的60%以上。'),
('经济管理学院', '经济学院前身是创办于1905年的经济科;已故经济学家彭迪先、张与九、蒋学模、胡寄窗、陶大镛、胡代光,以及当代学者刘诗白等曾先后在此任教或学习。');

-- 插入学生数据
insert into tb_student (stuid, stuname, stusex, stubirth, stuaddr, collid) 
values
    (1001, '杨逍', 1, '1990-3-4', '四川成都', 1),
    (1002, '任我行', 1, '1992-2-2', '湖南长沙', 1),
    (1033, '王语嫣', 0, '1989-12-3', '四川成都', 1),
    (1572, '岳不群', 1, '1993-7-19', '陕西咸阳', 1),
    (1378, '纪嫣然', 0, '1995-8-12', '四川绵阳', 1),
    (1954, '林平之', 1, '1994-9-20', '福建莆田', 1),
    (2035, '东方不败', 1, '1988-6-30', null, 2),
    (3011, '林震南', 1, '1985-12-12', '福建莆田', 3),
    (3755, '项少龙', 1, '1993-1-25', null, 3),
    (3923, '杨不悔', 0, '1985-4-17', '四川成都', 3),
    (4040, '炼腰的隔壁老王', 1, '1989-1-1', '四川成都', 2);

-- 删除学生数据
delete from tb_student where stuid=4040;

-- 更新学生数据
update tb_student set stuname='杨过', stuaddr='湖南长沙' where stuid=1001;

-- 插入老师数据
insert into tb_teacher (teaid, teaname, teatitle, collid) values 
(1122, '张三丰', '教授', 1),
(1133, '宋远桥', '副教授', 1),
(1144, '杨逍', '副教授', 1),
(2255, '范遥', '副教授', 2),
(3366, '韦一笑', default, 3);

-- 插入课程数据
insert into tb_course (couid, couname, coucredit, teaid) values 
(1111, 'Python程序设计', 3, 1122),
(2222, 'Web前端开发', 2, 1122),
(3333, '操作系统', 4, 1122),
(4444, '计算机网络', 2, 1133),
(5555, '编译原理', 4, 1144),
(6666, '算法和数据结构', 3, 1144),
(7777, '经贸法语', 3, 2255),
(8888, '成本会计', 2, 3366),
(9999, '审计学', 3, 3366);

-- 插入选课数据
insert into tb_record (sid, cid, seldate, score) values 
(1001, 1111, '2017-09-01', 95),
(1001, 2222, '2017-09-01', 87.5),
(1001, 3333, '2017-09-01', 100),
(1001, 4444, '2018-09-03', null),
(1001, 6666, '2017-09-02', 100),
(1002, 1111, '2017-09-03', 65),
(1002, 5555, '2017-09-01', 42),
(1033, 1111, '2017-09-03', 92.5),
(1033, 4444, '2017-09-01', 78),
(1033, 5555, '2017-09-01', 82.5),
(1572, 1111, '2017-09-02', 78),
(1378, 1111, '2017-09-05', 82),
(1378, 7777, '2017-09-02', 65.5),
(2035, 7777, '2018-09-03', 88),
(2035, 9999, now(), null),
(3755, 1111, curdate(), null),
(3755, 8888, curdate(), null),
(3755, 9999, '2017-09-01', 92);


-- 查询所有学生信息,*不建议写,在实际使用过程中效率很低
select * from tb_student;
select stuid,stuname,stusex,stubirth,stuaddr,collid from tb_student;

-- 查询所有课程名称及学分(投影和别名)
select couname as 课程名称,coucredit as 学分 from tb_course;

-- 查询所有学生的姓名和性别
select stuname  as 姓名, case stusex when 1 then '男' when 2 then '未知' else '女' end as 性别 from tb_student

-- if函数并不是标准的SQL中的一部分,而是MySQL特有的函数,如果换成其他数据库,
-- 下面的查询语句可能不会能成立,例如在Oracle中,实现同样功能的函数叫decode。
select stuname as 姓名, if(stusex,'男','女') as '性别' from tb_student;

-- 查询所有老师的姓名和职称
select teaname as 姓名,teatitle as 职称 from tb_teacher;

-- 查询所有女学生的姓名和出生日期(筛选)
select stuname,stubirth from tb_student where stusex=0;

-- 查询所有80后学生的姓名、性别和出生日期(筛选)
-- 在执行筛选操作时,如果有多个条件,可以通过and和or关键字进行组合
-- 也可以使用not将条件变成其对立面(逻辑变反)
select stuname,stubirth from tb_student where stubirth >= '1980-1-1' and stubirth <='1989-12-31';

-- between ... and ... 两端都是闭区间
select stuname,stubirth from tb_student where stubirth between '1980-1-1' and  '1989-12-31';

-- 查询姓”杨“的学生姓名和性别(模糊)
-- %通配字符,表示0次或者多次,_0个或者1个,
select stuname,stusex from tb_student where stuname like '杨%';

-- 查询姓”杨“名字两个字的学生姓名和性别(模糊)
select stuname,stusex from tb_student where stuname like '杨_';

-- 查询姓”杨“名字三个字的学生姓名和性别(模糊),也可以用regexp来使用正则表达式,但是有点问题
select stuname,stusex from tb_student where stuname like '杨__';
select stuname,stusex from tb_student where stuname regexp '杨.';


-- 查询名字中有”不“字或“嫣”字的学生的姓名(模糊)
select stuname from tb_student where stuname like '%不%' or stuname like '%嫣%';
-- 优化性能,union并集还会去重,union all不会去重,
select stuname from tb_student where stuname like '%不%' 
union
select stuname from tb_student where stuname like '%嫣%';

-- 查询没有录入家庭住址的学生姓名(空值)
-- 在SQL中,null跟任何数据做任何运算结果都是null,而null值相当于布尔值的假(不成立),不等号<>表示
select stuname from tb_student where stuaddr=null;
select stuname from tb_student where stuaddr<=>null;
select stuname from tb_student where stuaddr is null;

-- 查询录入了家庭住址的学生姓名(空值)
select stuname from tb_student where stuaddr is not null;

-- 查询学生选课的所有日期(去重)
select distinct seldate from tb_record;

-- 查询学生的家庭住址(去重)
select distinct stuaddr from tb_student where stuaddr is not null;

-- 查询男学生的姓名和生日按年龄从大到小排列(排序)
-- order by 可以实现根据指定的字段排序,默认从小到大,asc - 升序,desc - 降序,不写表示默认
select stuname,stubirth from tb_student where stusex=1 order by stubirth asc;
-- 排序的两个数据相同
select stuname,stubirth from tb_student where stusex=1 order by stubirth asc ,stuid desc;
-- datediff()求取时间差,floor()向下取整
select stuname,floor(datediff(curdate(),stubirth)/365) as age from tb_student where stusex=1 order by age asc;


-- 聚合函数空值自动被忽略
-- 查询年龄最大的学生的出生日期(聚合函数)
select min(stubirth) from tb_student;

-- 查询年龄最小的学生的出生日期(聚合函数)
select max(stubirth) from tb_student;

-- 查询男女学生的人数(分组和聚合函数)
select stusex,count(stuid) as total from tb_student group by stusex order by total desc;

-- 查询课程编号为1111的课程的平均成绩(筛选和聚合函数)
select avg(score) from tb_record where cid=1111;

-- 查询有多少学生选了1111这门课
select count(sid) from tb_record where cid=1111;

-- 查询有多少学生选了1111这门课并参加了考试获得了成绩
select count(score) from tb_record where cid=1111;

-- 查询学号为1001的学生所有课程的平均分(筛选和聚合函数)
select avg(score) from tb_record where sid=1001;

-- 查询每个学生的学号和平均成绩(分组和聚合函数)
-- round(...,1) 保留一位小数
select sid,round(avg(score),1) from tb_record group by sid;

-- 查询平均成绩大于等于90分的学生的学号和平均成绩
-- 分组以后的筛选使用having子句
select sid,round(avg(score),1) avgscore from tb_record group by sid having avgscore>=90;

-- 查询年龄最大的学生的姓名(子查询)
select stuname from tb_student where stubirth=(select min(stubirth) from tb_student);

-- 查询年龄最小的学生姓名和年龄(子查询+运算)
select stuname,floor(datediff(curdate(),stubirth)/365) as age from tb_student where stubirth=(select max(stubirth) from tb_student);

-- 查询年龄最大的女学生
select stuname,floor(datediff(curdate(),stubirth)/365) as age from tb_student where stubirth=(select min(stubirth) from tb_student where stusex=0);

-- 查询年龄最大的男学生
select stuname,floor(datediff(curdate(),stubirth)/365) as age from tb_student where stubirth=(select min(stubirth) from tb_student where stusex=1) and stusex=1;


-- 查询选了两门以上的课程的学生姓名(子查询/分组条件/集合运算)
-- in / not in 判断元素在不在集合中的成员运算
select stuname from tb_student where stuid in (select sid from tb_record group by sid having count(sid)>2)

-- 查询学生姓名、课程名称(连接查询、连表查询)
-- 链接两张表的时候,如果没有链接条件,就会形成笛卡尔积(9*5)
-- 方法一:
select couname, coucredit, teaname from tb_course t1, tb_teacher t2 where t1.teaid=t2.teaid;

-- 方法二:内连接
select couname, coucredit, teaname from tb_course t1 inner join tb_teacher t2 on t1.teaid=t2.teaid;

-- 查询学生姓名、课程名称以及成绩(连接查询、连表查询)
select stuname,couname,score from tb_student,tb_record,tb_course where stuid=sid and couid=cid and score is not null;

select stuname,couname,score from tb_student inner join tb_record on stuid=sid inner join tb_course on couid=cid where score is not null;

-- 查询学生姓名、课程名称以及成绩(连接查询、连表查询),根据成绩排降序,只显示前五条
select stuname,couname,score from tb_student,tb_record,tb_course where stuid=sid and couid=cid and score is not null order by score desc limit 5;

-- 分页查询
-- 查询学生姓名、课程名称以及成绩(连接查询、连表查询),根据成绩排降序,取6-10条
select stuname,couname,score from tb_student,tb_record,tb_course where stuid=sid and couid=cid and score is not null order by score desc limit 5 offset 5;

select stuname,couname,score from tb_student,tb_record,tb_course where stuid=sid and couid=cid and score is not null order by score desc limit 5,5;

-- 查询学生姓名、课程名称以及成绩(连接查询、连表查询),根据成绩排降序,取11-15条
select stuname,couname,score from tb_student,tb_record,tb_course where stuid=sid and couid=cid and score is not null order by score desc limit 5 offset 10;

select stuname,couname,score from tb_student,tb_record,tb_course where stuid=sid and couid=cid and score is not null order by score desc limit 10,5;


-- 查询选课学生的姓名和平均成绩(子查询和连接查询)
-- 方法一:
select stuname, round(avg(score),1) as score from tb_student, tb_record where stuid=sid group by sid;
-- 方法二:
select stuname, avgscore from tb_student, (select sid,round(avg(score),1) as avgscore from tb_record group by sid) t2 where stuid=sid;

-- 查询每个学生的姓名和选课数量(左外连接和子查询)
-- 外连接:左外、右外、全外(MySQL不支持)
-- 内连接:只能查出满足链表条件的记录
-- 左外连接:保证左表的记录要完整的查出来,即便它并不满足连接条件
-- 查询语句出现在前面的表叫左表,出现在后面的表叫做右表
-- select from 子句 where子句 group by子句 having子句 order by子句 limit子句
select stuname,count(couid) from tb_student t1 left outer join tb_course t2  on stuid=sid left outer join tb_record t3 on couid=cid group by stuid;

select stuname, ifnull(total,0) from tb_student t1 left join (select sid,count(sid) as total from tb_record group by sid) t2 on stuid=sid;

互相学习共同进步!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值