MySQL语句
基础
>>> mysql -u root -pshow databases; # 显示所有use 数据库名; # 切换到指定数据库中show tables; # 查看当前数据中所有表# 添加地址# ip地址:% 表示所有create user '用户名'@'ip地址' identified by '密码';# 添加权限grant all privileges on 数据库名.* from '用户名'@'ip地址';grant all on *.* to '用户名'@'ip地址'# 修改密码set password for 用户名@localhost = password('新密码');
数据库操作
# 创建数据库, 指定字符为utf8编码create database 数据库名 default charset utf8;# 删除数据库drop database 数据库名;
表操作
# 创建表create table t1(id int not null,name char(10) engine=innodb default charset=utf8;# engine:# innodb 支持事务# myisam# 数据类型数字:tinyint:有符号:-128~127无符号:0 ~ 255int:bigint:float:double:decimal:字符串:char 定长,速度快,max:255varchar 变长,节省空间,速度慢 max:255text:max:65535字符mediumtext:max:2**24字符longtext:max:2**32字符ps:创建数据表时定长列往前放时间类型:date:年月日time:时分秒year:年datetime:年月日时分秒timestamp:枚举:enum集合:set# 列配置unsigned # 数字类型,无符号null/not null # 是否可以为空default 值 #默认值auto_increment # 自增,必须是主键primary key # 主键 约束(不能重复且不能为空),一个表中只能有一个# 清空表delete from t1;truncate table t1;# 删除表drop table t1;
desc 表名; # 查看表结构show create 表名; # 查看表创建sql语句show create 表名 /G; # 竖着看alter talbe 表名 auto_increment=1; # 修改表自增值
基本CURD
# 插入数据insert into t1(id, name) values(1, 'zhangsan');# 删除delete from t1 where id<5;# 修改update t1 set age=18 where id=5;# 查看数据select * from t1;
约束
主键
primary key
(不能重复且不能为空),一个表中只能有一个
唯一索引
unique
不能重复,可以为空
create table t1(id int auto_imcrenent primary key,ID_number char(15),unique unique_in(ID_number))
普通索引
create table t1(id int auto_imcrenent primary key,ID_number char(15),unique index(ID_number));
外键
create table userinfo(uid int auto_increment primary key,department_id int,constraint fk_user_depar foreign key(department_id) references department('id') # 外键约束)engine=innodb default charset=utf8;create table table department(id tinyint auto_increment primary key,title char(15))engine=innodb default charset=utf8;
数据操作
增
insert into t1(name,age) values ('zhangsan', 16),('lishi', 19)insert into t1(name, age) select name,age from t2
删
delete from t1 where id=5;
改
update t1 set name='wanwu',age=22 where id=6
查
AS 定义别名WHERE 条件条件:IN () 指定的值NOT IN () 不在指定的值BETWEEN n AND m 指定区间[n,m]LIKE 模糊查询 通配符 %:多个字符 _:一个字符LIMITLIMIT n # 前n条记录LIMIT m,n # 从第m条开始取n条, m从0开始ORDER BY排序:默认:顺序 ASC倒序: DESCGROUP BY分组聚合函数:COUNT(), MAX(), MIN(), SUM(), AVG()对聚合函数结果进行二次筛选必须使用 havingCASE WHEN 条件 THEN 为真值 ELSE 为假值 ENDIF(isnull())
连表操作
LEFT JOIN左连接,左边表全部显示SELECT * FROM t1 LEFT JOIN t2 ON t1.id = t2.tidRIGHT JOIN右连接,右边表全部显示union 上下连表, 自动去重UNION ALL 不去重
命令行
备份
备份数据表结构+数据mysqldump -u root db1 > db1.sql -p备份数据表结构mysqldump -u root -d db1> db1.sql -p执行文件# 先创建数据库create database db5 default charset utf8# 再执行文件mysqldump -u root -d db5 < db1.sql -p
视图
# 创建视图create view 视图名称 as sql# 修改视图alter view 视图名称 as sql# 删除视图drop view 视图名称
函数
内置函数
# 时间CURDATE() 当前时间 年-月-日CURRENT_TIMESTAMP() 年月日时分秒DATA_FORMAT() 时间格式化
自定义函数
DELIMITER //CREATE FUNCTION f1(p1 INT,p2 INT)RETURN INTBEGIN# 函数体DECLARE 变量名 类型 [DEFAULT 设置默认值];END //DELIMETER
存储过程
保存在MySQL上的一个别名(一堆sql语句)
用于替代程序员写SQL语句
# 创建存储过程DELIMITER //CREATE PROCEDURE p1()BEGIN# SQL语句END //DELIMETERCALL p1()# 传参数 INDELIMITER //CREATE PROCEDURE p2(IN n1 INT,IN n2 INT)BEGIN# SQL语句END //DELIMETER# 传参数 INDELIMITER //CREATE PROCEDURE p2(IN n1 INT,OUT n2 INT)BEGIN# SQL语句SET n2 = 1111;END //DELIMETERSET @v1 = 0; # 创建session级别的变量call(12, @v1); # @v1 = 1111
索引
- 约束
- 加速查找
索引种类:hash索引单值块范围btree索引二叉树建立索引:额外的文件保存特殊的数据结构查询快,插入更新删除慢命中索引
普通索引:CREATE INDEX 索引名 on 表名(列名)DROP INDEX 索引名 on 表名唯一索引:CREATE UNIQUE INDEX 索引组合索引多个字段组成索引最左前缀频繁查找的列创建索引创建索引命中索引like数据量比较大,避免使用函数or类型不一致!=order by组合索引,最左前缀
执行计划
# 预估执行操作explain sql语句type:查询的访问方式性能:all < index < range < index_merge < ref_or_null < ref < eq_erf < system/constALL 全表扫描index 全索引扫描RANGE 对索引进行范围查找INDEX_MERGE 合并索引ref 根据索引找一个或多个值eq_ref 连接时使用primary ley 或 unique 类型const 常量system 系统
大数据分页优化
记录当前页最大和最小id
- 页面只有上一页和下一页
``
下一页
记录当前页最大id page_max_id
where id > page_max_id limit 10
上一页
记录当前页最小id page_min_id
where id < page_min_id order by id limit 10 - 页面上有当前页左右页码
往下翻页 select_page > now_page
count = (select_page - now_page) * 10 # 10 每页显示条数
select * from user where id in(select id form (select id from user where id > page_max_id limit count) as t1 order by as.id desc limit 10))
python
pymysql
pip3 install pymysql
import pymysqlconn = pymysql.connect(host='loalhost', user='root', password='', database='db1', charset='utf8')cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 得到的结果集的元素为字典# sql = 'select * from tb1 where user=%s' % user # sql拼接会有SQL注入问题sql = 'select * from tb1 where user=%s and passwd=%s'cursor.excute(sql, user, passwd)cursor.excute(sql, [user, passwd])sql = 'select * from tb1 where user=%(u)s and passwd=%(p)s'cursor.excute(sql, {'u':user, 'p':passwd})res = cursor.fetchone() # 获取结果集中一条记录,指针后移一位# 移动指针cursor.scroll(位置,mode='relative') # 相对当前位置移动cursor.scroll(位置,mode='absolute') # 相对绝对位置移动res = cursor.fetchall() # 获取所有cursor.close()conn.close()
# 增删改sql = 'insert into userinfo(username,password) values(%s,%s)'res = cursor.execute(sql) # res 受影响的值# 可批量添加 , 只能insert时使用cursor.executemany(sql, [(...),(...)])# 获取插入的自增id, 多条同时插入时返回最后一条idcursor.lastrowidconn.commit() # 修改值时 需要commit
ORM框架 SQLAlchemy
关系对象映射
作用:
- 提供简单的规则
- 自动转换成SQL语句
