MySQL语句

基础

  1. >>> mysql -u root -p
  2. show databases; # 显示所有
  3. use 数据库名; # 切换到指定数据库中
  4. show tables; # 查看当前数据中所有表
  5. # 添加地址
  6. # ip地址:% 表示所有
  7. create user '用户名'@'ip地址' identified by '密码';
  8. # 添加权限
  9. grant all privileges on 数据库名.* from '用户名'@'ip地址';
  10. grant all on *.* to '用户名'@'ip地址'
  11. # 修改密码
  12. set password for 用户名@localhost = password('新密码');

数据库操作

  1. # 创建数据库, 指定字符为utf8编码
  2. create database 数据库名 default charset utf8;
  3. # 删除数据库
  4. drop database 数据库名;

表操作

  1. # 创建表
  2. create table t1(
  3. id int not null,
  4. name char(10
  5. ) engine=innodb default charset=utf8;
  6. # engine:
  7. # innodb 支持事务
  8. # myisam
  9. # 数据类型
  10. 数字:
  11. tinyint:
  12. 有符号:-128~127
  13. 无符号:0 ~ 255
  14. int
  15. bigint
  16. float
  17. double
  18. decimal
  19. 字符串:
  20. char 定长,速度快,max:255
  21. varchar 变长,节省空间,速度慢 max:255
  22. text
  23. max:65535字符
  24. mediumtext
  25. max:2**24字符
  26. longtext
  27. max:2**32字符
  28. ps:创建数据表时定长列往前放
  29. 时间类型:
  30. date:
  31. 年月日
  32. time:
  33. 时分秒
  34. year:
  35. datetime:
  36. 年月日时分秒
  37. timestamp:
  38. 枚举:
  39. enum
  40. 集合:
  41. set
  42. # 列配置
  43. unsigned # 数字类型,无符号
  44. null/not null # 是否可以为空
  45. default #默认值
  46. auto_increment # 自增,必须是主键
  47. primary key # 主键 约束(不能重复且不能为空),一个表中只能有一个
  48. # 清空表
  49. delete from t1;
  50. truncate table t1;
  51. # 删除表
  52. drop table t1;
  1. desc 表名; # 查看表结构
  2. show create 表名; # 查看表创建sql语句
  3. show create 表名 /G; # 竖着看
  4. alter talbe 表名 auto_increment=1; # 修改表自增值

基本CURD

  1. # 插入数据
  2. insert into t1(id, name) values(1, 'zhangsan');
  3. # 删除
  4. delete from t1 where id<5;
  5. # 修改
  6. update t1 set age=18 where id=5;
  7. # 查看数据
  8. select * from t1;

约束

主键

primary key
(不能重复且不能为空),一个表中只能有一个

唯一索引

unique
不能重复,可以为空

  1. create table t1(
  2. id int auto_imcrenent primary key,
  3. ID_number char(15),
  4. unique unique_in(ID_number)
  5. )

普通索引

  1. create table t1(
  2. id int auto_imcrenent primary key,
  3. ID_number char(15),
  4. unique index(ID_number)
  5. );

外键

  1. create table userinfo(
  2. uid int auto_increment primary key,
  3. department_id int,
  4. constraint fk_user_depar foreign key(department_id) references department('id') # 外键约束
  5. )engine=innodb default charset=utf8;
  6. create table table department(
  7. id tinyint auto_increment primary key,
  8. title char(15)
  9. )engine=innodb default charset=utf8;

数据操作

  1. insert into t1(name,age) values ('zhangsan', 16),('lishi', 19)
  2. insert into t1(name, age) select name,age from t2

  1. delete from t1 where id=5;

  1. update t1 set name='wanwu',age=22 where id=6

  1. AS 定义别名
  2. WHERE 条件
  3. 条件:
  4. IN () 指定的值
  5. NOT IN () 不在指定的值
  6. BETWEEN n AND m 指定区间[n,m]
  7. LIKE 模糊查询 通配符 %:多个字符 _:一个字符
  8. LIMIT
  9. LIMIT n # 前n条记录
  10. LIMIT m,n # 从第m条开始取n条, m从0开始
  11. ORDER BY
  12. 排序:
  13. 默认:顺序 ASC
  14. 倒序: DESC
  15. GROUP BY
  16. 分组
  17. 聚合函数:
  18. COUNT(), MAX(), MIN(), SUM(), AVG()
  19. 对聚合函数结果进行二次筛选必须使用 having
  20. CASE WHEN 条件 THEN 为真值 ELSE 为假值 END
  21. IF(isnull())

连表操作

  1. LEFT JOIN
  2. 左连接,左边表全部显示
  3. SELECT * FROM t1 LEFT JOIN t2 ON t1.id = t2.tid
  4. RIGHT JOIN
  5. 右连接,右边表全部显示
  6. union 上下连表, 自动去重
  7. UNION ALL 不去重

命令行

备份

  1. 备份数据表结构+数据
  2. mysqldump -u root db1 > db1.sql -p
  3. 备份数据表结构
  4. mysqldump -u root -d db1> db1.sql -p
  5. 执行文件
  6. # 先创建数据库
  7. create database db5 default charset utf8
  8. # 再执行文件
  9. mysqldump -u root -d db5 < db1.sql -p

视图

  1. # 创建视图
  2. create view 视图名称 as sql
  3. # 修改视图
  4. alter view 视图名称 as sql
  5. # 删除视图
  6. drop view 视图名称

函数

内置函数

  1. # 时间
  2. CURDATE() 当前时间 年-月-日
  3. CURRENT_TIMESTAMP() 年月日时分秒
  4. DATA_FORMAT() 时间格式化

自定义函数

  1. DELIMITER //
  2. CREATE FUNCTION f1(
  3. p1 INT,
  4. p2 INT)
  5. RETURN INT
  6. BEGIN
  7. # 函数体
  8. DECLARE 变量名 类型 [DEFAULT 设置默认值];
  9. END //
  10. DELIMETER

存储过程

保存在MySQL上的一个别名(一堆sql语句)
用于替代程序员写SQL语句

  1. # 创建存储过程
  2. DELIMITER //
  3. CREATE PROCEDURE p1()
  4. BEGIN
  5. # SQL语句
  6. END //
  7. DELIMETER
  8. CALL p1()
  9. # 传参数 IN
  10. DELIMITER //
  11. CREATE PROCEDURE p2(
  12. IN n1 INT,
  13. IN n2 INT
  14. )
  15. BEGIN
  16. # SQL语句
  17. END //
  18. DELIMETER
  19. # 传参数 IN
  20. DELIMITER //
  21. CREATE PROCEDURE p2(
  22. IN n1 INT,
  23. OUT n2 INT
  24. )
  25. BEGIN
  26. # SQL语句
  27. SET n2 = 1111;
  28. END //
  29. DELIMETER
  30. SET @v1 = 0; # 创建session级别的变量
  31. call(12, @v1); # @v1 = 1111

索引

  • 约束
  • 加速查找
  1. 索引种类:
  2. hash索引
  3. 单值块
  4. 范围
  5. btree索引
  6. 二叉树
  7. 建立索引:
  8. 额外的文件保存特殊的数据结构
  9. 查询快,插入更新删除慢
  10. 命中索引
  1. 普通索引:
  2. CREATE INDEX 索引名 on 表名(列名)
  3. DROP INDEX 索引名 on 表名
  4. 唯一索引:
  5. CREATE UNIQUE INDEX 索引
  6. 组合索引
  7. 多个字段组成索引
  8. 最左前缀
  9. 频繁查找的列创建索引
  10. 创建索引
  11. 命中索引
  12. like
  13. 数据量比较大,避免使用
  14. 函数
  15. or
  16. 类型不一致
  17. !=
  18. order by
  19. 组合索引,最左前缀

执行计划

  1. # 预估执行操作
  2. explain sql语句
  3. type
  4. 查询的访问方式
  5. 性能:all < index < range < index_merge < ref_or_null < ref < eq_erf < system/const
  6. ALL 全表扫描
  7. index 全索引扫描
  8. RANGE 对索引进行范围查找
  9. INDEX_MERGE 合并索引
  10. ref 根据索引找一个或多个值
  11. eq_ref 连接时使用primary ley unique 类型
  12. const 常量
  13. system 系统

大数据分页优化

记录当前页最大和最小id

  1. 页面只有上一页和下一页
    ``
    下一页
    记录当前页最大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
  2. 页面上有当前页左右页码
    往下翻页 select_page > now_page
    count = (select_page - now_page) * 10 # 10 每页显示条数
  1. select * from user where id in(
  2. select id form (
  3. select id from user where id > page_max_id limit count) as t1 order by as.id desc limit 10
  4. )
  5. )

python

pymysql

pip3 install pymysql

  1. import pymysql
  2. conn = pymysql.connect(host='loalhost', user='root', password='', database='db1', charset='utf8')
  3. cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 得到的结果集的元素为字典
  4. # sql = 'select * from tb1 where user=%s' % user # sql拼接会有SQL注入问题
  5. sql = 'select * from tb1 where user=%s and passwd=%s'
  6. cursor.excute(sql, user, passwd)
  7. cursor.excute(sql, [user, passwd])
  8. sql = 'select * from tb1 where user=%(u)s and passwd=%(p)s'
  9. cursor.excute(sql, {'u':user, 'p':passwd})
  10. res = cursor.fetchone() # 获取结果集中一条记录,指针后移一位
  11. # 移动指针
  12. cursor.scroll(位置,mode='relative') # 相对当前位置移动
  13. cursor.scroll(位置,mode='absolute') # 相对绝对位置移动
  14. res = cursor.fetchall() # 获取所有
  15. cursor.close()
  16. conn.close()
  1. # 增删改
  2. sql = 'insert into userinfo(username,password) values(%s,%s)'
  3. res = cursor.execute(sql) # res 受影响的值
  4. # 可批量添加 , 只能insert时使用
  5. cursor.executemany(sql, [(...),(...)])
  6. # 获取插入的自增id, 多条同时插入时返回最后一条id
  7. cursor.lastrowid
  8. conn.commit() # 修改值时 需要commit

ORM框架 SQLAlchemy

关系对象映射
作用:

  1. 提供简单的规则
  2. 自动转换成SQL语句