├── .gitignore ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MySQL 2 | 3 | - [索引](#索引) 4 | - [索引是什么](#索引是什么) 5 | - [为什么要用索引](#为什么要用索引) 6 | - [索引结构为什么采用B+Tree](#索引结构为什么采用btree) 7 | - [MySQL B+Tree索引体现形式](#mysql-btree索引体现形式) 8 | - [索引知识点](#索引知识点) 9 | - [索引使用注意点](#索引使用注意点) 10 | - [MySQL插拔式的存储引擎](#mysql插拔式的存储引擎) 11 | - [MySQL存储引擎介绍](#mysql存储引擎介绍) 12 | - [CSV存储引擎](#csv存储引擎) 13 | - [Archive存储引擎](#archive存储引擎) 14 | - [Memory存储引擎](#memory存储引擎) 15 | - [MyISAM](#myisam) 16 | - [InnoDB](#innodb) 17 | - [对比](#对比) 18 | - [MySQL体系结构及运行机理](#mysql体系结构及运行机理) 19 | - [MySQL体系结构](#mysql体系结构) 20 | - [MySQL查询优化](#mysql查询优化) 21 | - [客户端/服务端通信](#客户端服务端通信) 22 | - [查询状态](#查询状态) 23 | - [查询缓存](#查询缓存) 24 | - [查询优化处理](#查询优化处理) 25 | - [查询执行引擎](#查询执行引擎) 26 | - [返回客户端](#返回客户端) 27 | - [慢SQL](#慢sql) 28 | - [如何定位慢SQL](#如何定位慢sql) 29 | - [慢查询日志分析](#慢查询日志分析) 30 | - [慢查询日志分析工具](#慢查询日志分析工具) 31 | - [事务](#事务) 32 | - [什么是事务](#什么是事务) 33 | - [事务的ACID特性](#事务的acid特性) 34 | - [事务并发带来的的问题](#事务并发带来的的问题) 35 | - [事务的四种隔离级别](#事务的四种隔离级别) 36 | - [InnoDB引擎对事务隔离的支持程度](#innodb引擎对事务隔离的支持程度) 37 | - [数据库的锁](#数据库的锁) 38 | - [表锁和行锁](#表锁和行锁) 39 | - [InnoDB锁类型](#innodb锁类型) 40 | - [利用锁解决并发问题](#利用锁解决并发问题) 41 | - [死锁](#死锁) 42 | - [死锁的避免](#死锁的避免) 43 | - [MVCC](#MVCC) 44 | - [MVCC是什么](#mvcc是什么) 45 | - [MVCC版本控制案例](#mvcc版本控制案例) 46 | - [Undo Log](#undo-log) 47 | - [Undo Log是什么](#undo-log是什么) 48 | - [当前读、快照读](#当前读快照读) 49 | - [Redo Log](#redo-log) 50 | - [Redo Log是什么](#redo-log是什么) 51 | - [Redo Log补充](#redo-log补充) 52 | - [MySQL配置优化](#mysql配置优化) 53 | - [服务器参数](#服务器参数) 54 | - [寻找配置文件](#寻找配置文件) 55 | - [全局配置文件配置](#全局配置文件配置) 56 | - [内存参数配置](#内存参数配置) 57 | - [其他参数配置](#其他参数配置) 58 | - [数据库表设计](#数据库表设计) 59 | - [三大范式](#三大范式) 60 | - [完全满足范式的缺点](#完全满足范式的缺点) 61 | 62 | ## MySQL性能优化分析 63 | 64 | ### 索引 65 | 66 | 正确的创建合适的索引是提升数据库查询性能的基础。 67 | 68 | #### 索引是什么 69 | 索引是为了加速对表中数据行的检索而创建的一种分散存储的数据结构(硬盘级)。 70 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/%E7%B4%A2%E5%BC%95.jpeg) 71 | 72 | #### 为什么要用索引 73 | >索引能极大的减少存储引擎需要扫描的数据量。 74 | >索引可以把随机IO变成顺序IO。 75 | >索引可以帮助我们在进行分组、排序等操作时,避免使用临时表。 76 | 77 | #### 索引结构为什么采用B+Tree 78 | 二叉查找树 Binary Search Tree 79 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/%E4%BA%8C%E5%8F%89%E6%A0%91.jpeg) 80 | 81 | 平衡二叉查找树 Balanced Binary Search Tree 82 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/%E7%9B%B8%E5%AF%B9%E5%B9%B3%E8%A1%A1%E4%BA%8C%E5%8F%89%E6%A0%91.jpeg) 83 | 84 | 二叉树和平衡二叉树的缺点: 85 | 86 | 树结构太深 87 | 因为每个节点都存有数据,数据处的(高)深度决定着他的IO操作次数,IO操作耗时大。 88 | 89 | 数据存储太小 90 | 每一个磁盘块(节点/页,单位4kb)保存的数据量(远远不足4k)太小了 91 | 没有很好的利用操作磁盘IO的数据交换特性,也没有利用好磁盘IO的预读能力(空间局部性原理,预读8k、12k等),从而带来频繁的IO操作。 92 | 93 | 多路平衡查找树 B-Tree 94 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/%E7%BB%9D%E5%AF%B9%E5%B9%B3%E8%A1%A1%E4%BA%8C%E5%8F%89%E6%A0%91.jpeg) 95 | 96 | 平衡查找树的分支数量与关键字大小有关,可以大致认为:磁盘块的容量/关键字大小 = 平衡树分支数量。 97 | 98 | 加强版的多路平衡查找树 Mysql的B+Tree 99 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/B%2Btree.jpeg) 100 | 101 | B+Tree与B-Tree的区别 102 | >1.B+节点关键字搜索采用闭合区间 103 | 2.B+非叶节点不保存数据相关信息,只保存关键字和子节点的引用 104 | 3.B+关键字对应的数据保存在叶子节点中 105 | 4.B+叶子节点是顺序排列的,并且相邻节点具有顺序引用的关系 106 | 107 | 为什么选择B+Tree 108 | B+树是B-树的变种(PLUS版)多路绝对平衡查找树,他拥有B-树的优势 109 | B+树扫库、表能力更强 110 | B+树的磁盘读写能力更强 111 | B+树的排序能力更强 112 | B+树的查询效率更加稳定 113 | 114 | #### Mysql B+Tree索引体现形式 115 | Myisam 116 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/Myisam%E7%B4%A2%E5%BC%95.jpeg) 117 | 118 | 数据保存在MYD文件,索引文件为MYI。 119 | 120 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/Myisam%E5%8F%8C%E7%B4%A2%E5%BC%95.jpeg) 121 | 122 | Innodb 123 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/InnoDB%E7%B4%A2%E5%BC%95.jpeg) 124 | 125 | 未指定索引的情况下InnoDB会自动生成隐式索引。 126 | 127 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/InnoDB%E5%8F%8C%E7%B4%A2%E5%BC%95.jpeg) 128 | 129 | 这样设计的好处就是在数据迁移的时候辅助索引可以不做作相应的指向改变。 130 | 对于InnoDB的辅助索引,它的叶子节点存储的是索引值和指向主键索引的位置。 131 | 132 | Myisam VS Innodb 133 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/%E7%B4%A2%E5%BC%95%E5%AF%B9%E6%AF%94.jpeg) 134 | 135 | #### 索引知识点 136 | 列的离散性 137 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/%E7%B4%A2%E5%BC%95%E7%A6%BB%E6%95%A3%E6%80%A7.jpeg) 138 | 139 | 离散性低的索引会造成选择性差,无法寻找合适的分支,数库会使用全局扫描。类似男女这种字段如果简历索引则要简历位图索引。 140 | 141 | 最左匹配原则 142 | 对索引中关键字进行计算(对比),一定是从左往右依次进行(每一位),且不可跳过。 143 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/%E6%9C%80%E5%B7%A6%E5%8C%B9%E9%85%8D.jpeg) 144 | 145 | 联合索引 146 | 单列索引:节点中关键字[name] 147 | 联合索引:节点中关键字[name,phoneNum] 148 | 单列索引是特殊的联合索引 149 | 150 | 联合索引列选择原则 151 | >1.经常用的列优先 【最左匹配原则】 152 | 2.选择性(离散度)高的列优先【离散度高原则】 153 | 3.宽度小的列优先【最少空间原则】 154 | 155 | 覆盖索引 156 | 如果索引包含所有满足查询需要的数据的索引成为覆盖索引(Covering Index),也就是平时所说的不需要回表操作。 157 | 使用explain,可以通过输出的extra列来判断,对于一个索引覆盖查询,显示为using index,MySQL查询优化器在执行查询前会决定是否有索引覆盖查询。 158 | 覆盖索引可减少数据库IO,将随机IO变为顺序IO,可提高查询性能。 159 | 160 | #### 索引使用注意点 161 | 索引列的数据长度能少则少。 162 | 索引一定不是越多越好,越全越好,一定是建合适的。 163 | 匹配列前缀可用到索引 like 9999%,like %9999%、like %9999用不到索引; Where 条件中 not in 和 <>操作无法使用索引; 164 | 匹配范围值,order by 也可用到索引; 165 | 多用指定列查询,只返回自己想到的数据列,少用select *; 166 | 联合索引中如果不是按照索引最左列开始查找,无法使用索引; 167 | 联合索引中精确匹配最左前列并范围匹配另外一列可以用到索引; 168 | 联合索引中如果查询中有某个列的范围查询,则其右边的所有列都无法使用索引; 169 | 170 | ### Mysql插拔式的存储引擎 171 | 172 | #### Mysql存储引擎介绍 173 | >1.插拔式的插件方式。 174 | 2.存储引擎是指定在表之上的,即一个库中的每一个表都可以指定专用的存储引擎。 175 | 3.不管表采用什么样的存储引擎,都会在数据区,产生对应的一个frm文件(表结构定义描述文件)。 176 | 177 | #### CSV存储引擎 178 | 数据存储以CSV文件 179 | 特点: 180 | 不能定义索引、列定义必须为NOT NULL、不能设置自增列 -->不适用大表或者数据的在线处理 181 | CSV数据的存储用,隔开,可直接编辑CSV文件进行数据的编排 -->数据安全性低 182 | 注:编辑之后,要生效使用flush table XXX 命令 183 | 184 | 应用场景: 185 | 数据的快速导出导入 表格直接转换成CSV 186 | 187 | #### Archive存储引擎 188 | 压缩协议进行数据的存储 189 | 数据存储为ARZ文件格式 190 | 191 | 特点: 192 | 只支持insert和select两种操作 193 | 只允许自增ID列建立索引 194 | 行级锁 195 | 不支持事务 196 | 数据占用磁盘少 197 | 198 | 应用场景: 199 | 日志系统 200 | 大量的设备数据采集 201 | 202 | #### Memory存储引擎 203 | 数据都是存储在内存中,IO效率要比其他引擎高很多。 204 | 服务重启数据丢失,内存数据表默认只有16M。 205 | 206 | 特点: 207 | 支持hash索引,B tree索引,默认hash(查找复杂度0(1)) 208 | 字段长度都是固定长度varchar(32)=char(32) 209 | 不支持大数据存储类型字段如 blog,text 210 | 表级锁 211 | 212 | 应用场景: 213 | 等值查找热度较高数据 214 | 查询结果内存中的计算,大多数都是采用这种存储引擎 215 | 作为临时表存储需计算的数据 216 | 217 | #### Myisam 218 | Mysql5.5版本之前的默认存储引擎 219 | 较多的系统表也还是使用这个存储引擎 220 | 系统临时表也会用到Myisam存储引擎 221 | 222 | 特点: 223 | select count(*) from table 无需进行数据的扫描 224 | 数据(MYD)和索引(MYI)分开存储 225 | 表级锁 226 | 不支持事务 227 | 228 | #### Innodb 229 | Mysql5.5及以后版本的默认存储引擎 230 | 231 | Key Advantages: 232 | Its DML operations follow the ACID model [事务ACID] 233 | Row-level locking[行级锁] 234 | InnoDB tables arrange your data on disk to optimize queries based on primary keys[聚集索引(主键索引)方式进行数据存储] 235 | To maintain data integrity, InnoDB supports FOREIGN KEY constraints[支持外键关系保证数据完整性] 236 | 237 | #### 对比 238 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/%E5%BC%95%E6%93%8E%E5%AF%B9%E6%AF%94.jpeg) 239 | 240 | ### MySQL体系结构及运行机理 241 | 242 | #### MySQL体系结构 243 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/%E6%9E%B6%E6%9E%84.jpeg) 244 | 245 | Client Connectors 246 | 接入方 支持协议很多 247 | Management Serveices & Utilities 系统管理和控制工具,mysqldump、 mysql复制集群、分区管理等 248 | 249 | Connection Pool 250 | 连接池:管理缓冲用户连接、用户名、密码、权限校验、线程处理等需要缓存的需求 251 | 252 | SQL Interface 253 | SQL接口:接受用户的SQL命令,并且返回用户需要查询的结果 254 | 255 | Parser 256 | 解析器,SQL命令传递到解析器的时候会被解析器验证和解析。解析器是由Lex和YACC实现的 257 | 258 | Optimizer 259 | 查询优化器,SQL语句在查询之前会使用查询优化器对查询进行优化 260 | 261 | Cache和Buffer(高速缓存区) 262 | 查询缓存,如果查询缓存有命中的查询结果,查询语句就可以直接去查询缓存中取数据 263 | 264 | pluggable storage Engines 插件式存储引擎。存储引擎是MySql中具体的与文件打交道的子系统 265 | 266 | file system 267 | 文件系统,数据、日志(redo,undo)、索引、错误日志、查询记录、慢查询等 268 | 269 | ### MySQL查询优化 270 | 271 | #### MySQL查询执行路径 272 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/%E6%9F%A5%E8%AF%A2%E6%B5%81%E7%A8%8B.jpeg) 273 | 274 | >1.mysql 客户端/服务端通信 275 | 2.查询缓存 276 | 3.查询优化处理 277 | 4.查询执行引擎 278 | 5.返回客户端 279 | 280 | #### 客户端/服务端通信 281 | 282 | Mysql客户端与服务端的通信方式是“半双工”; 283 | 284 | 全双工:双向通信,发送同时也可以接收 285 | 半双工:双向通信,同时只能接收或者是发送,无法同时做操作 286 | 单工:只能单一方向传送 287 | 288 | 半双工通信: 在任何一个时刻,要么是有服务器向客户端发送数据,要么是客户端向服务端发送数据,这两个动作不能同时发生。所以我们无法也无需将一个消息切成小块进行传输。 289 | 290 | 特点和限制: 客户端一旦开始发送消息,另一端要接收完整个消息才能响应。 291 | 客户端一旦开始接收数据没法停下来发送指令。 292 | 293 | #### 查询状态 294 | 对于一个mysql连接,或者说一个线程,时刻都有一个状态来标识这个连接正在做什么 295 | 查看命令 show full processlist / show processlist 296 | https://dev.mysql.com/doc/refman/5.7/en/general-thread-states.html (状态全集) 297 | 298 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/%E6%9F%A5%E8%AF%A2%E5%8F%82%E6%95%B0.jpeg) 299 | 300 | Sleep 301 | 线程正在等待客户端发送数据 302 | Query 303 | 连接线程正在执行查询 304 | Locked 305 | 线程正在等待表锁的释放 306 | Sorting result 307 | 线程正在对结果进行排序 308 | Sending data 309 | 向请求端返回数据 310 | 311 | 可通过kill {id} 的方式进行连接的杀掉 312 | 313 | #### 查询缓存 314 | 工作原理: 315 | >缓存SELECT操作的结果集和SQL语句; 316 | 新的SELECT语句,先去查询缓存,判断是否存在可用的记录集; 317 | 318 | 判断标准: 319 | 与缓存的SQL语句,是否完全一样,区分大小写(简单认为存储了一个key-value结构,key为sql,value为sql查询结果集)。 320 | 321 | query_cache_type 322 | >值:0 -– 不启用查询缓存,默认值; 323 | 值:1 -– 启用查询缓存,只要符合查询缓存的要求,客户端的查询语句和记录集都可以缓存起来,供其他客户端使用,加上SQL_NO_CACHE将不缓存。 324 | 值:2 -– 启用查询缓存,只要查询语句中添加了参数:SQL_CACHE,且符合查询缓存的要求,客户端的查询语句和记录集,则可以缓存起来,供其他客户端使用。 325 | 326 | query_cache_size 327 | >允许设置query_cache_size的值最小为40K,默认1M,推荐设置为:64M/128M; 328 | 329 | query_cache_limit 330 | >限制查询缓存区最大能缓存的查询记录集,默认设置为1M 331 | 332 | `show status like 'Qcache%' `命令可查看缓存情况。 333 | 334 | 不会缓存的情况 335 | >1.当查询语句中有一些不确定的数据时,则不会被缓存。如包含函数NOW(),CURRENT_DATE()等类似的函数,或者用户自定义的函数,存储函数,用户变量等都不会被缓存。 336 | 2.当查询的结果大于query_cache_limit设置的值时,结果不会被缓存。 337 | 3.对于InnoDB引擎来说,当一个语句在事务中修改了某个表,那么在这个事务提交之前,所有与这个表相关的查询都无法被缓存。因此长时间执行事务,会大大降低缓存命中率。 338 | 4.查询的表是系统表 339 | 5.查询语句不涉及到表 340 | 341 | 为什么mysql默认关闭了缓存开启 342 | >1.在查询之前必须先检查是否命中缓存,浪费计算资源。 343 | 2.如果这个查询可以被缓存,那么执行完成后,MySQL发现查询缓存中没有这个查询,则会将结果存入查询缓存,这会带来额外的系统消耗。 344 | 3.针对表进行写入或更新数据时,将对应表的所有缓存都设置失效。 345 | 4.如果查询缓存很大或者碎片很多时,这个操作可能带来很大的系统消耗。 346 | 347 | 缓存适用业务场景 348 | 以读为主的业务,数据生成之后就不常改变的业务 349 | 比如门户类、新闻类、报表类、论坛类等 350 | 351 | #### 查询优化处理 352 | 查询优化处理的三个阶段: 353 | >1.解析sql通过lex词法分析,yacc语法分析将sql语句解析成解析树。 354 | https://www.ibm.com/developerworks/cn/linux/sdk/lex/ 355 | 2.预处理阶段 根据mysql的语法的规则进一步检查解析树的合法性,如:检查数据的表和列是否存在,解析名字和别名的设置,还会进行权限的验证。 356 | 3.查询优化器 优化器的主要作用就是找到最优的执行计划。 357 | 358 | 查询优化器如何找到最优执行计划 359 | • 使用等价变化规则 360 | >数据表的关联并不总是按照查询语句的顺序进行。 361 | 362 | • 将外链接转化为内连接 363 | >并不是所有的OUTER JOIN都必须以外链接的方式进行。 364 | 365 | • 使用等价变化规则 366 | >5=5 and a>5 改写成 a>5 367 | a5 and a=5 368 | 369 | • 优化count 、min、max等函数 370 | >min函数只需找索引最左边 371 | max函数只需找索引最右边 372 | myisam引擎count(*) 373 | 374 | • 覆盖索引扫描 375 | • 子查询优化 376 | • 提前终止查询 377 | >用了limit关键字或者使用不存在的条件 378 | 379 | • IN的优化 380 | >先进行排序,再采用二分查找的方式 381 | ... 382 | 383 | Mysql的查询优化器基于成本计算的原则,会尝试各种执行计划,以数据抽样的方式进行试验(随机的读取一个4K的数据块进行分析)。 384 | 385 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/%E6%9F%A5%E8%AF%A2%E4%BC%98%E5%8C%96.jpeg) 386 | 387 | id 388 | select查询的序列号,标识执行的顺序 389 | >1.id相同,执行顺序由上至下。 390 | 2.id不同,如果是子查询,id的序号会递增,id值越大优先级越高,越先被执行。 391 | 3.id相同又不同即两种情况同时存在,id如果相同,可以认为是一组,从上往下顺序执行;在所有组中,id值越大,优先级越高,越先执行。 392 | 393 | select_type 394 | 查询的类型,主要是用于区分普通查询、联合查询、子查询等 395 | >SIMPLE:简单的select查询,查询中不包含子查询或者union 396 | PRIMARY:查询中包含子部分,最外层查询则被标记为primary 397 | SUBQUERY/MATERIALIZED: 398 | SUBQUERY表示在select或where列表中包含了子查询 399 | MATERIALIZED表示where后面in条件的子查询 400 | UNION:若第二个select出现在union之后,则被标记为union 401 | UNION RESULT:从union表获取结果的select 402 | 403 | table 404 | 查询涉及到的表 405 | 直接显示表名或者表的别名 406 | 由ID为M,N 查询union产生的结果 407 | 由ID为N查询生产的结果 408 | 409 | type 410 | 访问类型,sql查询优化中一个很重要的指标,结果值从好到坏依次是: 411 | system > const > eq_ref > ref > range > index > ALL 412 | >system:表只有一行记录(等于系统表),const类型的特例,基本不会出现,可以忽略不计。 413 | const:表示通过索引一次就找到了,const用于比较primary key或者unique索引。 414 | eq_ref:唯一索引扫描,对于每个索引键,表中只有一条记录与之匹配。常见于主键或唯一索引扫描。 415 | ref:非唯一性索引扫描,返回匹配某个单独值的所有行,本质是也是一种索引访问。 416 | range:只检索给定范围的行,使用一个索引来选择行。 417 | index:Full Index Scan,索引全表扫描,把索引从头到尾扫一遍。 418 | ALL:Full Table Scan,遍历全表以找到匹配的行。 419 | 420 | possible_keys 421 | 查询过程中有可能用到的索引 422 | 423 | key 424 | 实际使用的索引,如果为NULL,则没有使用索引 425 | 426 | rows 427 | 根据表统计信息或者索引选用情况,大致估算出找到所需的记录所需要读取的行数 428 | 429 | filtered 430 | 表示返回结果的行数占需读取行数的百分比,filtered的值越大越好 431 | 432 | Extra 433 | 十分重要的额外信息 434 | >1.Using filesort : mysql对数据使用一个外部的文件内容进行了排序,而不是按照表内的索引进行排序读取。 435 | 2.Using temporary: 使用临时表保存中间结果,也就是说mysql在对查询结果排序时使用了临时表,常见于order by 或 group by。 436 | 3.Using index:表示相应的select操作中使用了覆盖索引(Covering Index),避免了访问表的数据行,效率高。 437 | 4.Using where : 使用了where过滤条件。 438 | 5.select tables optimized away: 基于索引优化MIN/MAX操作或者MyISAM存储引擎优化COUNT(*)操作,不必等到执行阶段在进行计算,查询执行计划生成的阶段即可完成优化。 439 | 440 | #### 查询执行引擎 441 | 调用插件式的存储引擎的原子API的功能进行执行计划的执行。 442 | 443 | #### 返回客户端 444 | >1.有需要做缓存的,执行缓存操作。 445 | 2.增量的返回结果:开始生成第一条结果时,mysql就开始往请求方逐步返回数据。 446 | 好处: mysql服务器无须保存过多的数据,浪费内存;用户体验好,马上就拿到了数据。 447 | 448 | ### 慢SQL 449 | 450 | #### 如何定位慢SQL 451 | >1.业务驱动 452 | 2.测试驱动 453 | 3.慢查询日志 454 | ``` 455 | show variables like 'slow_query_log' 456 | set global slow_query_log = on 457 | set global slow_query_log_file = '/var/lib/mysql/test-slow.log' 458 | set global log_queries_not_using_indexes = on 459 | set global long_query_time = 0.1 (秒) 460 | ``` 461 | 462 | #### 慢查询日志分析 463 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/%E6%85%A2%E6%9F%A5%E8%AF%A2%E6%97%A5%E5%BF%97.jpeg) 464 | 465 | ``` 466 | Time :日志记录的时间 467 | User@Host:执行的用户及主机 468 | Query_time:查询耗费时间 469 | Lock_time 锁表时间 470 | Rows_sent 发送给请求方的记录条数 471 | Rows_examined 语句扫描的记录条数 472 | SET timestamp 语句执行的时间点 473 | select .... 执行的具体语句 474 | ``` 475 | 476 | #### 慢查询日志分析工具 477 | ``` 478 | mysqldumpslow -t 10 -s at /var/lib/mysql/test-slow.log 479 | ``` 480 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/%E6%85%A2%E6%9F%A5%E8%AF%A2%E5%B7%A5%E5%85%B7.jpeg) 481 | 482 | 其他工具 483 | >mysqlsla 484 | pt-query-digest 485 | 486 | ### 事务 487 | 488 | #### 什么是事务 489 | 数据库操作的最小工作单元,是作为单个逻辑工作单元执行的一系列操作; 490 | 事务是一组不可再分割的操作集合(工作逻辑单元); 491 | 492 | 典型事务场景(转账): 493 | ``` 494 | update user_account set balance = balance - 1000 where userID = 3; 495 | update user_account set balance = balance + 1000 where userID = 1; 496 | ``` 497 | 498 | mysql中如何开启事务: 499 | ``` 500 | begin / start transaction -- 手工 501 | commit / rollback -- 事务提交或回滚 502 | set session autocommit = on/off; -- 设定事务是否自动开启 503 | 504 | JDBC 编程: 505 | connection.setAutoCommit(boolean); 506 | 507 | Spring 事务AOP编程: 508 | expression=execution(cn.zyf.dao.*.*(..)) 509 | ``` 510 | 511 | #### 事务的ACID特性 512 | >原子性(Atomicity) 最小的工作单元,整个工作单元要么一起提交成功,要么全部失败回滚。 513 | 一致性(Consistency) 事务中操作的数据及状态改变是一致的,即写入资料的结果必须完全符合预设的规则,不会因为出现系统意外等原因导致状态的不一致。 514 | 隔离性(Isolation) 一个事务所操作的数据在提交之前,对其他事务的可见性设定(一般设定为不可见)。 515 | 持久性(Durability) 事务所做的修改就会永久保存,不会因为系统意外导致数据的丢失。 516 | 517 | #### 事务并发带来的的问题 518 | 脏读 519 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/%E8%84%8F%E8%AF%BB.jpeg) 520 | 521 | 不可重复读 522 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/%E4%B8%8D%E5%8F%AF%E9%87%8D%E5%A4%8D%E8%AF%BB.jpeg) 523 | 524 | 幻读 525 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/%E5%B9%BB%E8%AF%BB.jpeg) 526 | 527 | #### 事务的四种隔离级别 528 | SQL92 ANSI/ISO标准: 529 | http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt 530 | 531 | >Read Uncommitted(未提交读) --未解决并发问题 532 | 事务未提交对其他事务也是可见的,脏读(dirty read) 533 | Read Committed(提交读) --解决脏读问题 534 | 一个事务开始之后,只能看到自己提交的事务所做的修改,不可重复读(nonrepeatable read) 535 | Repeatable Read (可重复读) --解决不可重复读问题 536 | 在同一个事务中多次读取同样的数据结果是一样的,这种隔离级别未定义解决幻读的问题 537 | Serializable(串行化) --解决所有问题 最高的隔离级别,通过强制事务的串行执行 538 | 539 | 查看mysql的设置的事务隔离级别 540 | select global.@@tx_isolation; select @@tx_isolation; 541 | 542 | #### InnoDB引擎对事务隔离的支持程度 543 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/InnoDB%E9%9A%94%E7%A6%BB%E7%BA%A7%E5%88%AB.jpeg) 544 | 545 | ### 数据库的锁 546 | 547 | #### 表锁和行锁 548 | 549 | 锁是用于管理不同事务对共享资源的并发访问 550 | 表锁与行锁的区别: 551 | >锁定粒度:表锁 > 行锁 552 | 加锁效率:表锁 > 行锁 553 | 冲突概率:表锁 > 行锁 554 | 并发性能:表锁 < 行锁 555 | 556 | InnoDB存储引擎支持行锁和表锁(另类的行锁) 557 | 558 | #### InnoDB锁类型 559 | 共享锁(行锁):Shared Locks 560 | 排它锁(行锁):Exclusive Locks 561 | 意向锁共享锁(表锁):IntentionShared Locks 562 | 意向锁排它锁(表锁):Intention Exclusive Locks 563 | 自增锁:AUTO-INC Locks 564 | 565 | 行锁的算法 566 | 记录锁 Record Locks 567 | 间隙锁 Gap Locks 568 | 临键锁 Next-key Locks 569 | 570 | 共享锁: 571 | 又称为读锁,简称S锁,顾名思义,共享锁就是多个事务对于同一数据可以共享一把锁,都能访问到数据,但是只能读不能修改; 572 | 573 | 加锁释锁方式: 574 | select * from users WHERE id=1 LOCK IN SHARE MODE; 575 | commit/rollback 576 | 577 | 排他锁: 578 | 又称为写锁,简称X锁,排他锁不能与其他锁并存,如一个事务获取了一个数据行的排他锁,其他事务就不能再获取该行的锁(共享锁、排他锁),只有该获取了排他锁的事务是可以对数据行进行读取和修改,(其他事务要读取数据可来自于快照)。 579 | 580 | 加锁释锁方式: 581 | delete / update / insert 默认加上X锁 582 | SELECT * FROM table_name WHERE ... FOR UPDATE 583 | commit/rollback 584 | 585 | InnoDB行锁究竟锁住了什么 586 | >InnoDB的行锁是通过给索引上的索引项加锁来实现的。 587 | 只有通过索引条件进行数据检索,InnoDB才使用行级锁,否则,InnoDB 将使用表锁(锁住索引的所有记录)。 588 | 二级索引(辅助索引)去更新数据,会把二级索引和聚集索引都上锁。 589 | 590 | 意向共享锁(IS) 591 | 表示事务准备给数据行加入共享锁,即一个数据行加共享锁前必须先取得该表的IS锁,意向共享锁之间是可以相互兼容的。 592 | 593 | 意向排它锁(IX) 594 | 表示事务准备给数据行加入排他锁,即一个数据行加排他锁前必须先取得该表的IX锁,意向排它锁之间是可以相互兼容的。 595 | 596 | 意向锁(IS、IX)是InnoDB数据操作之前自动加的,不需要用户干预。 597 | >意义:当事务想去进行锁表时,可以先判断意向锁是否存在,存在时则可快速返回该表不能启用表锁。 598 | 599 | 自增锁:AUTO-INC Locks 600 | 针对自增列自增长的一个特殊的表级别锁 601 | show variables like 'innodb_autoinc_lock_mode'; 602 | 默认取值1,代表连续,事务未提交ID永久丢失 603 | 604 | 临键锁Next-key locks: 605 | 锁住记录+区间(左开右闭) 606 | 当sql执行按照索引进行数据的检索时,查询条件为范围查找(between and、<、>等)并有数 据命中则此时SQL语句加上的锁为Next-key locks,锁住索引的记录+区间(左开右闭) 607 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/%E4%B8%B4%E9%94%AE%E9%94%81.jpeg) 608 | 609 | 间隙锁Gap locks: 610 | 锁住数据不存在的区间(左开右开) 611 | 当sql执行按照索引进行数据的检索时,查询条件的数据不存在,这时SQL语句加上的锁即为 Gap locks,锁住索引不存在的区间(左开右开) 612 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/%E9%97%B4%E9%9A%99%E9%94%81.jpeg) 613 | 614 | Gap只在RR事务隔离级别存在。 615 | 616 | 记录锁Record locks: 617 | 锁住具体的索引项 618 | 当sql执行按照唯一性(Primary key、Unique key)索引进行数据的检索时,查询条件等值匹 配且查询的数据是存在,这时SQL语句加上的锁即为记录锁Record locks,锁住具体的索引项 619 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/%E8%AE%B0%E5%BD%95%E9%94%81.jpeg) 620 | 621 | #### 利用锁解决并发问题 622 | 解决脏读 623 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/%E8%A7%A3%E5%86%B3%E8%84%8F%E8%AF%BB.jpeg) 624 | 625 | 解决不可重复读 626 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/%E8%A7%A3%E5%86%B3%E4%B8%8D%E5%8F%AF%E9%87%8D%E5%A4%8D%E8%AF%BB.jpeg) 627 | 628 | 解决幻读 629 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/%E8%A7%A3%E5%86%B3%E5%B9%BB%E8%AF%BB.jpeg) 630 | 631 | #### 死锁 632 | 多个并发事务(2个或者以上); 633 | 每个事务都持有锁(或者是已经在等待锁); 634 | 每个事务都需要再继续持有锁; 635 | 事务之间产生加锁的循环等待,形成死锁。 636 | 637 | #### 死锁的避免 638 | 1.类似的业务逻辑以固定的顺序访问表和行。 639 | 2.大事务拆小。大事务更倾向于死锁,如果业务允许,将大事务拆小。 640 | 3.在同一个事务中,尽可能做到一次锁定所需要的所有资源,减少死锁概率。 641 | 4.降低隔离级别,如果业务允许,将隔离级别调低也是较好的选择 642 | 5.为表添加合理的索引。可以看到如果不走索引将会为表的每一行记录添 加上锁(或者说是表锁) 643 | 644 | ### MVCC 645 | ``` 646 | ex1:tx1: set session autocommit=off; 647 | update users set lastUpdate=now() where id =1; 648 | 在未做commit/rollback操作之前 649 | 在其他的事务我们能不能进行对应数据的查询(特别是加上了X锁的数据) 650 | tx2: select * from users where id > 1; 651 | select * from users where id = 1; 652 | ``` 653 | ``` 654 | ex2:tx1: begin 655 | select * from users where id =1 ; 656 | tx2: begin 657 | tx1: update users set lastUpdate=now() where id =1; 658 | select * from users where id =1; 659 | ``` 660 | 661 | 这两个案例从结果上来看是一致的,底层实现是一样的吗?跟MVCC有什么关系么? 662 | 663 | #### MVCC是什么 664 | MVCC:Multiversion concurrency control (多版本并发控制) 665 | 666 | 普通话解释: 并发访问(读或写)数据库时,对正在事务内处理的数据做多版本的管理。以达到用来避免写操作的堵塞,从而引发读操作的并发问题。 667 | 668 | MVCC插入逻辑流程 669 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/MVCC%E6%8F%92%E5%85%A5.jpeg) 670 | 671 | MVCC删除逻辑流程 672 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/MVCC%E5%88%A0%E9%99%A4.jpeg) 673 | 674 | MVCC修改逻辑流程 675 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/MVCC%E4%BF%AE%E6%94%B9.jpeg) 676 | 677 | MVCC查询逻辑流程 678 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/MVCC%E6%9F%A5%E8%AF%A2.jpeg) 679 | 680 | #### MVCC版本控制案例 681 | 数据准备: 682 | ``` 683 | insert into teacher(name,age) value ('seven',18) ; 684 | insert into teacher(name,age) value ('qing',20) ; 685 | ``` 686 | ``` 687 | tx1: 688 | begin; ----------1 689 | select * from users ; ----------2 690 | commit; 691 | ``` 692 | ``` 693 | tx2: 694 | begin; ----------3 695 | update teacher set age =28 where id =1; ----------4 696 | commit; 697 | ``` 698 | 699 | 控制案例1 (1,2,3,4,2) 700 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/MVCC%E6%A1%88%E4%BE%8B1.jpeg) 701 | 702 | 控制案例2 (3,4,1,2) 703 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/MVCC%E6%A1%88%E4%BE%8B2.jpeg) 704 | 705 | ### Undo Log 706 | 707 | #### Undo Log是什么 708 | undo意为取消,以撤销操作为目的,返回指定某个状态的操作。 709 | undo log指事务开始之前,在操作任何数据之前,首先将需操作的数据备份到一个地方 (Undo Log)。 710 | 711 | UndoLog是为了实现事务的原子性而出现的产物。 712 | 713 | Undo Log实现事务原子性: 714 | 事务处理过程中如果出现了错误或者用户执行了ROLLBACK语句,Mysql可以利用Undo Log中的备份将数据恢复到事务开始之前的状态。 715 | 716 | UndoLog在MySQL InnoDB存储引擎中用来实现多版本并发控制。 717 | 718 | Undo log实现多版本并发控制: 719 | 事务未提交之前,Undo保存了未提交之前的版本数据,Undo 中的数据可作为数据旧版本快照供其他并发事务进行快照读。 720 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/Undo.jpeg) 721 | 722 | #### 当前读、快照读 723 | 快照读: 724 | SQL读取的数据是快照版本,也就是历史版本,普通的SELECT就是快照读。 725 | InnoDB快照读,数据的读取将由 cache(原本数据) + undo(事务修改过的数据) 两部分组成。 726 | 727 | 当前读: 728 | SQL读取的数据是最新版本。通过锁机制来保证读取的数据无法通过其他事务进行修改。 729 | UPDATE、DELETE、INSERT、SELECT ... LOCK IN SHARE MODE、SELECT ... FOR UPDATE都是当前读。 730 | 731 | ### Redo Log 732 | 733 | #### Redo Log是什么 734 | Redo,顾名思义就是重做。以恢复操作为目的,重现操作。 735 | Redo log指事务中操作的任何数据,将最新的数据备份到一个地方 (Redo Log)。 736 | 737 | 不是随着事务的提交才写入的,而是在事务的执行过程中,便开始写入redo中。具体的落盘策略可以进行配置。 738 | 739 | RedoLog是为了实现事务的持久性而出现的产物。 740 | 741 | Redo Log实现事务持久性: 防止在发生故障的时间点,尚有脏页未写入磁盘,在重启mysql服务的时候,根据redo log进行重做,从而达到事务的未入磁盘数据进行持久化这一特性。 742 | ![](https://github.com/YufeizhangRay/image/blob/master/MySQL/Redo.jpeg) 743 | 744 | #### Redo Log补充 745 | 指定Redolog记录在{datadir}/ib_logfile1&ib_logfile2,可通过innodb_log_group_home_dir配置指定目录存储。 746 | 747 | 一旦事务成功提交且数据持久化落盘之后,此时Redo log中的对应事务数据记录就失去了意义,所以Redo log的写入是日志文件循环写入的。 748 | >指定Redo log日志文件组中的数量 innodb_log_files_in_group 默认为2。 749 | 指定Redo log每一个日志文件最大存储量innodb_log_file_size 默认48M。 750 | 指定Redo log在cache/buffer中的buffer池大小innodb_log_buffer_size 默认16M。 751 | 752 | Redo buffer 持久化Redo log的策略, Innodb_flush_log_at_trx_commit: 753 | >取值 0 每秒提交 Redo buffer --> Redo log OS cache -->flush cache to disk[可能丢失一秒内的事务数据]。 754 | 取值 1 默认值,每次事务提交执行Redo buffer --> Redo log OS cache -->flush cache to disk[最安全,性能最差的方式]。 755 | 取值 2 每次事务提交执行Redo buffer --> Redo log OS cache 再每一秒执行 ->flush cache to disk操作。 756 | 757 | ### MySQL配置优化 758 | 759 | #### 服务器参数 760 | 基于参数的作用域 761 | 全局参数 762 | set global autocommit = ON/OFF; 763 | 764 | 会话参数(会话参数不单独设置则会采用全局参数) 765 | set session autocommit = ON/OFF; 766 | 767 | 注意: 768 | 全局参数的设定对于已经存在的会话无法生效 769 | 会话参数的设定随着会话的销毁而失效 770 | 全局类的统一配置建议配置在默认配置文件中,否则重启服务会导致配置失效 771 | 772 | #### 寻找配置文件 773 | mysql --help 寻找配置文件的位置和加载顺序 774 | ``` 775 | Default options are read from the following files in the given order: 776 | /etc/my.cnf 777 | /etc/mysql/my.cnf 778 | /usr/etc/my.cnf 779 | ~/.my.cnf 780 | ``` 781 | ``` 782 | mysql --help | grep -A 1 'Default options are read from the following files in the given order' 783 | ``` 784 | 785 | #### 全局配置文件配置 786 | 最大连接数配置 787 | max_connections 788 | 789 | 系统句柄数配置 790 | /etc/security/limits.conf 791 | ulimit -a 792 | 793 | mysql句柄数配置 794 | /usr/lib/systemd/system/mysqld.service 795 | 796 | ``` 797 | port = 3306 798 | socket = /tmp/mysql.sock 799 | basedir = /usr/local/mysql 800 | datadir = /data/mysql 801 | pid-file = /data/mysql/mysql.pid 802 | user = mysql 803 | bind-address = 0.0.0.0 804 | 805 | max_connections=2000 806 | lower_case_table_names = 0 #表名区分大小写 807 | server-id = 1 808 | tmp_table_size=16M 809 | transaction_isolation = REPEATABLE-READ 810 | ready_only=1 811 | ... 812 | ``` 813 | 814 | #### 内存参数配置 815 | 每一个connection内存参数配置: 816 | sort_buffer_size connection排序缓冲区大小 817 | 建议256K(默认值)-> 2M之内 818 | 当查询语句中有需要文件排序功能时,马上为connection分配配置的内存大小 819 | 820 | join_buffer_size connection关联查询缓冲区大小 821 | 建议256K(默认值)-> 1M之内 当查询语句中有关联查询时,马上分配配置大小的内存用这个关联查询,所以有可能在一个查询语句中会分配很多个关联查询缓冲区。 822 | 823 | 上述配置4000连接占用内存: 824 | 4000*(0.256M+0.256M) = 2G 825 | 826 | Innodb_buffer_pool_size 827 | innodb buffer/cache的大小(默认128M) 828 | 829 | Innodb_buffer_pool 830 | >数据缓存 831 | 索引缓存 832 | 缓冲数据 833 | 内部结构 834 | 835 | 大的缓冲池可以减小多次磁盘I/O访问相同的表数据以提高性能。 836 | 837 | 参考计算公式: 838 | Innodb_buffer_pool_size = (总物理内存 - 系统运行所用 - connection 所用)* 90% 839 | 840 | #### 其他参数配置 841 | wait_timeout 842 | 服务器关闭非交互连接之前等待活动的秒数。 843 | 844 | innodb_open_files 845 | 限制Innodb能打开的表的个数。 846 | 847 | innodb_write_io_threads 848 | innodb_read_io_threads 849 | innodb使用后台线程处理innodb缓冲区数据页上的读写 I/O(输入输出)请求。 850 | 851 | innodb_lock_wait_timeout 852 | InnoDB事务在被回滚之前可以等待一个锁定的超时秒数。 853 | 854 | https://www.cnblogs.com/wyy123/p/6092976.html 常见配置的帖子 855 | 856 | ### 数据库表设计 857 | 858 | #### 三大范式 859 | 第一范式(1NF): 860 | 字段具有原子性,不可再分。所有关系型数据库系统都满足第一范式,数据库表中的字段都是单一属性的,不可再分。 861 | 862 | 第二范式(2NF): 863 | 要求实体的属性完全依赖于主键。所谓完全依赖是指不能存在仅依赖主键一部分的属性,如果存在,那么这个属性和主关键字的这一部分应该分离出来形成一个新的实体, 新实体与原实体之间是一对多的关系。为实现区分通常需要为表加上一个列,以存储各个实例的惟一标识。简而言之,第二范式就是属性完全依赖主键。 864 | 865 | 第三范式(3NF): 866 | 满足第三范式(3NF) 必须先满足第二范式(2NF)。 简而言之,第三范式(3NF)要求一个数据库表中不包含已在其它表中已包含的非主键信息。 867 | 868 | 简单一点: 869 | >1.每一列只有一个单一的值,不可再拆分。 870 | 2.每一行都有主键能进行区分。 871 | 3.每一个表都不包含其他表已经包含的非主键信息。 872 | 873 | #### 完全满足范式的缺点 874 | 充分的满足第一范式设计将为表建立太量的列。 875 | 数据从磁盘到缓冲区,缓冲区脏页到磁盘进行持久的过程中,列的数量过多会导致性能下降。过多的列影响转换和持久的性能。 876 | 877 | 过分的满足第三范式化造成了太多的表关联。 878 | 表的关联操作将带来额外的内存和性能开销。 879 | 880 | 使用InnoDB引擎的外键关系进行数据的完整性保证。 881 | 外键表中数据的修改会导致Innodb引擎对外键约束进行检查,就带来了额外的开销。 882 | --------------------------------------------------------------------------------