数据库简介:
关系型数据库
内部表格数据有关联性,redis是非关联型数据库
命令后面都要加分号
1.基本概念
数据库:一些关联数据表的集合
数据表:数据以矩阵形式存储的表格
列
行
冗余:将相互关联的数据表需要频繁查取的信息在一张表上复制一份
优点:加快数据查询速度
缺点:增加内存压力和修改数据压力
主键:没一个样本只有一个主键
外键:用于关联列表之间相互关联
索引:用于查找数据的标签
组合键:多个列表组合构成索引
2.基本命令
show databases;
查看所有数据库
show 表名;
查看表的信息
select * from 表名\G;
查看数据表的信息
show columns from user;
查看数据表的列的信息
create database 数据库名字;
创建一个数据库,该数据库默认仅支持英文
drop database 数据库名字;
删除一个数据库
show create database 数据库名字;
展示创建数据库的具体信息
create database 数据库名字 charset utf8;
创建一个支持中文格式的数据库
show index from 数据库名字;
显示数据库详细索引信息
3.数据类型(数值,时间,字符串)
数值:
tinyint 1字节 小整数值
smallint 2字节 大整数值
mediumint 3字节 大整数值
int/integer 4字节 大整数值
bigint 8字节 极大整数值
float 4字节 单精度,浮点数值
double 8字节 双精度,浮点数值
decimal None 小数
时间:
date 3字节 日期值
time 3字节 时间值或持续时间
year 1字节 年份值
datetime 8字节 时间值与日期混合
timestamp 4字节 混合时间和日期值,时间戳
字符串类型:
char 0-255字节 定长字符串
varchar 0-65535字节 变长字符串
tinyblob 0-255字节 二进制字符串
tinytext 0-255字节 短文本字符串
blob 0-65535字节 二进制形式的长文本数据
text 0-65535字节 长文本数据
mediumblob 0-16777215字节 二进制形式中等长度文本数据
mediumtext 0-16777215字节 中等长度文本数据
4.操作数据表
创建数据表:
create table student(
id int auto_increment,
name char(32) not null,
age int not null,
register_date date not null,
primary key (id));
插入数据样本:
insert into student (name,age,register_date) value("Tom",23,"2020-07-02");
查询数据样本:
select * from student where register_date="2020-07%";
查找出所有在七月份注册的学生
修改数据样本:
update student set name="Williams",age=99 where id=3;
删除样本:
delete from student where name="Jim";
排序样本:
select * from student order by age asc; 按升序排列
select * from student order by age desc; 按降序排列
分组统计:
select name,count(*) from student group by name;
根据名字计算年龄:
select name,sum(age) from student group by name;
计算总共年龄:
select coalesce(name,"Total Number"),sun(age) from student group by name with rollup;
在数据表中添加字段:
alter table student add sex char(32);
设置数据表中的字段数据不能为空:
alter table student modify sex enum("F","M") not null;
删除数据表中的字段:
alter table student drop register_date;
修改字段名称:
alter table student change sex gender char(32) not null;
修改字段的默认值:
alter table student modify age int(12) not null default 100;
判断是否为空:
is null;
is not null;
表的连接
求两个表的交集:
select * from A inner join B on A.a=B.b;
or select A.*,B.* from A,B where A.a=B.b;
求两个表的差集:
select * from A left join B on A.a=B.b; 取出A有B没有的样本
or select * from B right join A on A.a=B.b;
求两个表的并集:
select * from A left join B on A.a=B.b union
select * from A right join B on A.a=B.b;
5.事务
事务的四种必备属性:
原子性:一组事务,要么成功,要么撤回
稳定性:有非法数据,事务撤回
隔离性:事务独立运行,要是执行结果影响其他事务,其他事务撤回
可靠性:执行任务是软硬件崩溃,系统会自动保存进度
创建事务:
begin;
各种命令
rollback; 回滚到事务之前的状态并结束事务
6.索引
索引会提高检索速度,但是会降低修改表单的速度
创建索引:
create index ID on
alter table add index on
创建表的时候直接指定
create table A(
index
显示索引:
show index from student;
删除索引:
drop index index_name on student;
7.ORM mysql封装
好用的Python的MySQL模块:sqlalchemy