关系型数据库-MySQL:MySQL操作

发布时间 2023-07-14 21:51:04作者: _老衲
MySQL :: MySQL 8.0 Reference Manual

SQL语言主要用于存取数据、查询数据、更新数据和管理关系数据库系统,SQL语言由IBM开发。SQL语言分为3种类型:

  • DDL(数据库定义语言): CREATE、DROP、ALTER等
  • DML(数据库操纵语言): INSERT、DELETE、UPDATE、SELECT
  • DCL(数据库控制语言):GRANT、REVOKE

1、注释、终止符等

1)注释
单行:-- 
多行:/*  SQL语言  */2)终止符
默认“;”或/g。/G:表格行列颠倒显示。
修改终止符:delimiter 终止符
(3)变量 
@用户变量@@系统变量

2、账号操作

(1)用户账号管理

①增
  create user '用户名'@'IP地址' identified by '密码';
②删
  drop user '用户名'@'IP地址';
③改
  rename user '用户名'@'IP地址' to '新用户名'@'IP地址';  -- 修改用户名
  alter user '用户名'@'IP地址' identified by '新密码';  -- 修改密码
④查
  select user,host from mysql.user;
ps:IP地址用通配符
%表示任意IP地址;   用户权限相关数据保存在mysql数据库的user表中,所以也可以直接对其进行操作(不建议)

 (2)用户授权管理

①查看授权
show grants ;                                  -- 查看自己权限
show grants for '用户'@'IP地址'-- 查看用户权限
②授权
grant  权限 on 数据库.表 to '用户'@'IP地址' [identified by '密码'];
③取消授权
revoke 权限 on 数据库.表 from '用户'@'IP地址'

ps:*_*表示所有数据库的所有所有数据表
     all privileges  除grant外的所有权限
     select          仅查权限
    select,insert   查和插入权限
     ...
     usage                   无访问权限
    alter                   使用alter table
    alter routine           使用alter procedure和drop procedure
    create                  使用create table
    create routine          使用create procedure
    create temporary tables 使用create temporary tables
     create user             使用create userdrop user、rename user和revoke  all privileges
    create view             使用create view
    delete                  使用delete
    drop                    使用drop table
    execute                 使用call和存储过程
    file                    使用select into outfile 和 load data infile
    grant option            使用grant 和 revoke
    index                   使用index
     insert                  使用insert
    lock tables             使用lock table
    process                 使用show full processlist
     select                  使用select
    show databases          使用show databases
    show view               使用show view
    update                  使用update
    reload                  使用flush
    shutdown                使用mysqladmin shutdown(关闭MySQL)
    super                   ??使用change master、kill、logs、purge、master和set global。还允许mysqladmin????调试登陆
    replication client      服务器位置的访问
    replication slave       由复制从属使用          
关于权限

flush privileges:将数据读取到内存中,从而立即生效。

3、数据库操作

①查询数据库
  show databases;
②选择数据库
  use 数据库名;
③增
  create database [if not exists] 数据库名;
④删
  drop database [if exists] 数据库名;
⑤导入数据库中文件
 mysqldump -u用户名 -p密码 数据库名 <文件路径
⑥导出数据库中文件
 mysqldump -u用户名 -p密码 数据库名称 >导出文件路径          --结构+数据
 mysqldump -u用户名 -p密码 -d 数据库名称 >导出文件路径       --结构 

4、数据表操作

4.1数据表操作

create table 表名
(列名 数据类型 [null/not null] [default 值] [auto_increment primary key],
[constraint 外键名 foreign key (列名) references 主表(列名)]);
ps:自增一般与主键连用;主键可以是单列或多列,其值必须唯一。 删
drop table 表名; 查 show tables; --查看所有数据表 show create table 表名/G --查看数据表创建信息 desc 表名; --查看数据表头信息

4.2数据表头操作

alter table 表名 add 列名 类型
删
alter table 表名 drop column 列名
改
alter table 表名 modify 列名 类型;  -- 修改类型
alter table 表名 change 原列名 新列名 类型; -- 修改列名,类型
alter table 表名 modify 列名1 类型 first/after 列名2;  -- 修改列顺序

自增
alter table 表名 auto_increment=新值;--基于表
    修改会话变量
    show session variables like 'auto_inc%';
    set session auto_increment_increment=新值;
    set session auto_increment_offset=新值;
    修改全局变量
    show global  variables like 'auto_inc%';
    set global auto_increment_increment=新值;
    set global auto_increment_offset=新值;
默认值
alter table 表名 alter 列名 set default 新值;--修改默认值
alter table 表名 alter 列名 drop default--删除默认值
外键
alter table 从表 add constraint 外键名 foreign key 从表(列名) references 主表(列名);--增加外键
alter table 表名 drop foreign key 外键名;--删除外键

4.3索引

索引可以加速查找和约束,但会降低增删改执行速度。

(1)索引种类

①普通索引(index):仅加速查找
增:alter table 表名 add index 索引名(列名1,...);
  create index 索引名 on 表名(列名1,...); 删:alter table 表名 drop index 索引名;
  drop index 索引名 on 表名; ②唯一索引(unique):加速查找+不可重复 增:alter table 表名 add unique 索引名(列名,...);
  create unique index 索引名 on 表名(列名1,...); 删:alter table 表名 drop index 索引名;
  drop index 索引名 on 表名; ③主键索引(primary key):加速查找+不可重复+不为空 增:alter table 表名 add primary key(列名1,...); 删:alter table 表名 drop primary key; --无自增列 alter table 表名 modify 列名 类型, drop primary key; --有自增列 ④组合索引:遵循最左前缀匹配 ⑤全文索引:(使用第三方工具)对文本的内容进行分词,进行搜索

(2)索引存储结构

  • hash索引:查询单值快(存储位置无序),查询范围慢。
  • btree索引:二叉树

(3)使用索引

1)不会命中索引的情况
① like '%xx'
    select * from tb1 where name like '%cn';
② 条件中使用函数
    select * from tb1 where reverse(name) = 'wupeiqi';
③ or!=><
    select * from tb1 where nid = 1 or email = 'seven@live.com';
④ 查找类型不一致(主键除外)
    如果列是字符串类型,传入条件是必须用引号引起来,不然...
    select * from tb1 where name = 999;
⑤ 组合索引最左前缀
    如果组合索引为:(name,email)
    name and email       -- 使用索引
    name                 -- 使用索引
    email                -- 不使用索引

2)其他注意事项
① 避免使用select *查找count(1)或count(列) 代替 count(*)
③ 创建表时尽量时 char 代替 varchar
④ 使用连接(JOIN)来代替子查询(Sub-Queries),连表时注意条件类型需一致
⑤ 索引散列值(重复多)不适合建索引,例:性别不适合
⑥ 组合索引代替多个单列索引(经常使用多个条件查询时)

(4)慢日志查询

1)开启慢日志(通过修改变量(内存)或配置文件设置来开启)

slow_query_log = OFF                            是否开启慢日志记录
long_query_time = 2                              时间限制,超过此时间,则记录
slow_query_log_file = 文件路径        日志文件
log_queries_not_using_indexes = OFF     为使用索引的搜索是否记录

注:查看当前配置信息:
       show variables like '%query%'
     修改当前配置:
    set global 变量名 = 值

2)查看MySQL慢日志

mysqldumpslow -s at -a 文件路径

"""
--verbose    版本
--debug      调试
--help       帮助
 
-v           版本
-d           调试模式
-s ORDER     排序方式
             what to sort by (al, at, ar, c, l, r, t), 'at' is default
              al: average lock time
              ar: average rows sent
              at: average query time
               c: count
               l: lock time
               r: rows sent
               t: query time
-r           反转顺序,默认文件倒序拍。reverse the sort order (largest last instead of first)
-t NUM       显示前N条just show the top n queries
-a           不要将SQL中数字转换成N,字符串转换成S。don't abstract all numbers to N and strings to 'S'
-n NUM       abstract numbers with at least n digits within names
-g PATTERN   正则匹配;grep: only consider stmts that include this string
-h HOSTNAME  mysql机器名或者IP;hostname of db server for *-slow.log filename (can be wildcard),
             default is '*', i.e. match all
-i NAME      name of server instance (if using mysql.server startup script)
-l           总时间中不减去锁定时间;don't subtract lock time from total time
"""
指令说明

(5)执行计划(估算执行快慢)

explain + SQL查询语句  :用于显示SQL执行信息参数,根据参考信息可以进行SQL优化

mysql> explain select * from userinfo;
+----+-------------+----------+------------+------+---------------+------+---------+------+---------+----------+-------+
| id | select_type | table    | partitions | type | possible_keys | key  | key_len | ref  | rows    | filtered | Extra |
+----+-------------+----------+------------+------+---------------+------+---------+------+---------+----------+-------+
|  1 | SIMPLE      | userinfo | NULL       | ALL  | NULL          | NULL | NULL    | NULL | 1573978 |   100.00 | NULL  |
+----+-------------+----------+------------+------+---------------+------+---------+------+---------+----------+-------+
1 row in set, 1 warning (0.00 sec)
id:查询顺序标识
   如:mysql> explain select * from (select nid,name from tb1 where nid < 10) as B;
   +----+-------------+------------+-------+---------------+---------+---------+------+------+-------------+
  | id | select_type | table      | type  | possible_keys | key     | key_len | ref  | rows | Extra       |
  +----+-------------+------------+-------+---------------+---------+---------+------+------+-------------+
  |  1 | PRIMARY     | <derived2> | ALL   | NULL          | NULL    | NULL    | NULL |    9 | NULL        |
  |  2 | DERIVED     | tb1        | range | PRIMARY       | PRIMARY | 8       | NULL |    9 | Using where |
  +----+-------------+------------+-------+---------------+---------+---------+------+------+-------------+
  特别的:如果使用union连接气值可能为null

select_type:查询类型
  SIMPLE          简单查询
  PRIMARY         最外层查询
  SUBQUERY        映射为子查询
   DERIVED         子查询
  UNION           联合
  UNION RESULT    使用联合的结果
     ...

table:正在访问的表名

type:查询时的访问方式,
  性能:all < index < range < index_merge < ref_or_null < ref < eq_ref < system/const
  ALL             全表扫描,对于数据表从头到尾找一遍
            select * from tb1;
            特别的:如果有limit限制,则找到之后就不在继续向下扫描
                 select * from tb1 where email = 'seven@live.com'
                    select * from tb1 where email = 'seven@live.com' limit 1;
                   虽然上述两个语句都会进行全表扫描,第二句使用了limit,则找到一个后就不再继续扫描。
  INDEX           全索引扫描,对索引从头到尾找一遍
                    select nid from tb1;
   RANGE           对索引列进行范围查找
                   select *  from tb1 where name < 'alex';
                    PS:
                      between and
                      in
                      >   >=  <   <=  操作
                      注意:!=> 符号
    INDEX_MERGE:合并索引,使用多个单列索引搜索
                    select *  from tb1 where name = 'alex' or nid in (11,22,33);
    REF:根据索引查找一个或多个值
                     select *  from tb1 where name = 'seven';
    EQ_REF:连接时使用primary key 或 unique类型
                    select tb2.nid,tb1.name from tb2 left join tb1 on tb2.nid = tb1.nid;
   CONST:常量
                    表最多有一个匹配行,因为仅有一行,在这行的列值可被优化器剩余部分认为是常数,const表很快,因为它们只读取一次。
                    select nid from tb1 where nid = 2 ;

SYSTEM :系统
               =表仅有一行(=系统表)。这是const联接类型的一个特例。
               =select * from (select nid from tb1 where nid = 1) as A;

possible_keys:可能使用的索引

key:真实使用的

key_len:MySQL中使用索引字节长度

rows:mysql估计为了找到所需的行而要读取的行数 ------ 只是预估值

extra:该列包含MySQL解决查询的详细信息
     “Using index”:此值表示mysql将使用覆盖索引,以避免访问表。不要把覆盖索引和index访问类型弄混了。
     “Using where”:这意味着mysql服务器将在存储引擎检索行后再进行过滤,许多where条件里涉及索引中的列,当(并且如果)它读取索引时,就能被存储引擎检验,因此不是所有带where子句的查询都会显示“Using where”。有时“Using where”的出现就是一个暗示:查询可受益于不同的索引。
     “Using temporary”:这意味着mysql在对查询结果排序时会使用一个临时表。
     “Using filesort”:这意味着mysql会对结果使用一个外部索引排序,而不是按索引次序从表里读取行。mysql有两种文件排序算法,这两种排序方式都可以在内存或者磁盘上完成,explain不会告诉你mysql将使用哪一种文件排序,也不会告诉你排序会在内存里还是磁盘上完成。
     “Range checked for each record(index map: N)”:这个意味着没有好用的索引,新的索引将在联接的每一行上重新估算,N是显示在possible_keys列中索引的位图,并且是冗余的。
详细信息

 (6)分页

解放方案:①缓存②记录当前页自增类的最大值或最小值

1)正序
往后翻几页:
select  * from 表名
where  id >= (select id from (select id from 表名 where id > 当前页最小值  limit 每页项目 *[选择页-当前页]) as A order by A.id desc limit 1)  
limit 每页数据;
往前翻几页:
select  * from 表名
where  id >= (select id from (select id from 表名 where id < 当前页最小值  limit 每页项目 *[选择页-当前页]) as A limit 1)  
limit 每页数据;
第二种方案

4.4数据类型

常用的数据类型分为数值、字符串、时间。

(1)数值类型

  1)整数:自8.0.17版本后,整数类型仅支持[UNSIGNED]属性

  2)小数

DECIMAL[(M=10[,D=0])]:最大位数(M)为65,支持的最大小数位数(D)为30。精确值。
② FLOAT:精确到小数后7位数
③ DOUBLE:精确到小数后15位数
④ FLOAT(P):p=0~24,相当于FLOAT;p=25~53,相当于DOUBLE。
小数

(2)字符串类型

字符串数据类型为 CHARVARCHARBLOBTEXTENUM 和 SET

1)CHAR和VARCHAR
①:CHAR[M=1]:定长字符串,最大长度255个字符;检索时自动去除尾部空格。
②:VARCHAR[M]:不定长字符串,最大长度65535个字符(有效长度不超多65535字节,储存时1字节或2字节长度前缀加上数据。
2)BOLB和TEXT
① TINYBLOB:最大长度255(2^8-1)字节,使用1字节前缀存储长度信息
② BLOB:最大长度65,535(2^16-1)字节,使用2字节前缀存储长度信息
③ MEDIUMBLOB:最大长度16,777,2152^24-1)字节,使用3字节前缀存储长度信息
④ LONGBLOB:最大长度(2^32-1)字节或4GB字节,使用4字节前缀存储长度信息
⑤ TINYTEXT:最大长度255(2^8-1)字符,使用1字节前缀存储长度信息
⑥ TEXT:最大长度65,535(2^16-1)字符,使用2字节前缀存储长度信息
⑦ MEDIUMTEXT:最大长度16,777,2152^24-1)字符,使用3字节前缀存储长度信息
⑧ LONGTEXT:最大长度(2^32-1)字符或4GB字符,使用4字节前缀存储长度信息
3)ENUM和SET
① ENUM(‘v1’,‘v2’…):一个enum最多可包含65,535个不同的元素。单个ENUM元素的最大支持长度是255(文字长度)。枚举值内部对应一个索引,从1开始。字符串对象只能取单一元素。
② SET(‘v1’,‘v2’…):一个SET列最多可包含64个不同的元素。单个SET元素的最大支持长度是255(文字长度)。字符串对象可取所有元素的任意组合。

ps:文件过大时,上传文件路径到文件中。
字符串类型

(3)时间

5、数据表内容操作

1)增
    insert into 表 (列名,列名...) values (值,值,值...);
     insert into 表 (列名,列名...) values (值,值,值...),(值,值,值...);
    insert into 表 (列名,列名...) select (列名,列名...) from 表;

(2)删
     delete from[where 条件]--自增值一起删除
     truncate table 表;             --仅清除数据,不改变自增数值
3)改
     updateset 列名=[where 条件];

(4)查
     select ... from[连表[where 条件[分组[having 条件[排序[限制]]]]]][组合]
 1)条件
     select * fromwhere ... and/between..and../in/not in...;
     通配符
     select * fromwhere name like 'ale%'  -- ale开头的所有(多个字符串)
     select * fromwhere name like 'ale_'  -- ale开头的所有(一个字符)
 2)限制:隐藏部分表格,函数结果不表
     select * from 表 limit 5;            -- 前5行
     select * from 表 limit 4,5;          -- 从第4行开始的5行
     select * from 表 limit 5 offset 4    -- 从第4行开始的5行
 3)排序
     select * fromorder byasc              -- 根据 “列” 从小到大排列
     select * fromorder bydesc             -- 根据 “列” 从大到小排列
     select * fromorder by 列1 desc,列2 asc    -- 根据 “列1” 从大到小排列,如果相同则按列2从小到大排序
 4)分组:合并列中的重复数据;聚合函数必须在having条件中
    select distinct 列名 form 表     --去重,效率低
     select num,nid fromwhere nid > 10 group by num,nid order nid desc
     select num ,count(*)fromgroup by num having max(id) > 10
 5)连表:左右连接
 ①逗号连表
     select * from 表1,表2  --笛卡尔积现象
     select A.num, A.name, B.name  from A,B where A.nid = B.nid  --无对应关系则不显示
 ②join连表
     select A.num, A.name, B.name from A inner join B on A.nid = B.nid  --无对应关系则不显示
     select A.num, A.name, B.name from A left join B on A.nid = B.nid   --A表所有显示,如果B中无对应关系,则值为null
     select A.num, A.name, B.name  from A right join B on A.nid = B.nid  --B表所有显示,如果B中无对应关系,则值为null
 6)组合:上下连表
     select nickname from A union select name from B     --自动去重
     select nickname from A union all select name  from B   --不去重
 7)子表:子表可以调用主表
     select 列名,(select 列名 from 表) form 表 --子表仅能取单类数据,且行数不能高于主表

 6、进阶内容