├── .gitignore ├── LICENSE ├── README.md ├── SQL ├── README.md ├── 信息函数.md ├── 修改表.md ├── 加密函数.md ├── 多表更新.md ├── 子查询.md ├── 字符串函数.md ├── 存储过程.md ├── 插入记录.md ├── 数值运算与比较运算.md ├── 数据库操作.md ├── 日期时间函数.md ├── 更新记录.md ├── 权限管理.md ├── 查询.md ├── 用户管理.md ├── 索引.md ├── 约束.md ├── 聚合函数.md ├── 自定义函数.md └── 表基本操作.md ├── SQL优化 ├── IN操作.md └── README.md ├── sakila.sql ├── world.sql ├── 接口编程 └── C++ │ ├── 01 连接数据库.md │ ├── 02 Statement.md │ ├── 03 PreparedStatement.md │ ├── 04 ResultSet.md │ ├── 05 事务.md │ └── README.md └── 高级概念 ├── MySQL命令.md ├── README.md ├── 备份还原.md └── 存储引擎.md /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | # Compiled Object files 3 | *.slo 4 | *.lo 5 | *.o 6 | *.obj 7 | 8 | # Precompiled Headers 9 | *.gch 10 | *.pch 11 | 12 | # Compiled Dynamic libraries 13 | *.so 14 | *.dylib 15 | *.dll 16 | 17 | # Fortran module files 18 | *.mod 19 | 20 | # Compiled Static libraries 21 | *.lai 22 | *.la 23 | *.a 24 | *.lib 25 | 26 | # Executables 27 | *.exe 28 | *.out 29 | *.app 30 | 31 | *.DS_Store 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MySQL-docs 2 | 个人整理MySQL笔记。包括SQL语法,MySQL管理,C/C++接口编程 3 | -------------------------------------------------------------------------------- /SQL/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guodongxiaren/MySQL-docs/a274ad111c1b04d2f2ed16e3949d89c2a6d650ef/SQL/README.md -------------------------------------------------------------------------------- /SQL/信息函数.md: -------------------------------------------------------------------------------- 1 | 信息函数 2 | ------------ 3 | |名称|函数| 4 | |------|-------| 5 | |CONNECTIOIN_ID|连接ID 6 | |DATABASE|当前数据库 7 | |LAST_INSERT_ID|最后插入记录ID 8 | |USER|当前用户 9 | |VERSION|版本信息 10 | ###CONNECTION_ID 11 | 第一连接就是1,以此类推。 12 | ###DATABASE 13 | ###LAST_INSERT_ID 14 | 当一条语句插入多条记录的时候,它只返回第一条记录的ID。 15 | ###USER 16 | 返回当前用户。MYSQL中的用户的完整用户名是 **用户名@登录主机** 17 | ###VERSION 18 | MySQL版本号 19 | -------------------------------------------------------------------------------- /SQL/修改表.md: -------------------------------------------------------------------------------- 1 | 修改数据表 2 | ========== 3 | 所有的数据表的修改SQL语句的开头都是ALTER TABLE+表名称。 4 | ##给表改名 5 | ```sql 6 | ALTER TABLE tb_name RENAME {TO|AS} tb_new_name; 7 | ``` 8 | 另外有个写法是: 9 | ```sql 10 | RENAME TABLE tb_name TO tb_new_name; 11 | ``` 12 | 这句可以批量修改多个表的名称。 13 | >尽量不要随意修改表的名称。对视图有影响。 14 | 15 | ##添加/删除列 16 | ###插入列 17 | ```sql 18 | ALTER TABLE tb_name ADD [COLUMN] col_name column_definition [FIRST|AFTER col_name]; 19 | ``` 20 | 默认会插入到表的最下面,指定FIRST,则置于最上面,或者用`AFTER col_name` 指定为`col_name`的下面。 21 | ###删除列 22 | ```sql 23 | ALTER TABLE tb_name DROP col_name,DROP.....; 24 | ``` 25 | 可以一次性删除多个列。 26 | ##修改列 27 | ###修改列定义 28 | 即修改列的属性。 29 | ```sql 30 | ALTER TABLE tb_name MODIFY col_name column_definition [FIRST|AFTER col_name]; 31 | ``` 32 | 比如: 33 | ```sql 34 | ALTER TABLE test ADD id SMALLINT unsigned KEY auto_increment first; 35 | ``` 36 | key可以表示主键,无需primary。fitrst表示插入的位置。 37 | >如果要修改的列已经是`主键`了,则修改列定义的时候再加上`主键`字段会报错。 38 | 39 | ###修改列名 40 | ```sql 41 | ALTER TABLE tb_name CHANGE col_name col_new_name column_definition [FIRST|AFTER col_name]; 42 | ``` 43 | 修改列名时,新列名后面要指明数据类型。 44 | ###修改列顺序 45 | 其实同上,具体比如: 46 | ```sql 47 | ALTER TABLE `user` CHANGE `join_time` `join_time` DATE NULL DEFAULT NULL AFTER `role`; 48 | ``` 49 | 把join_time列放到role列后面。 50 | 51 | 52 | ##修改约束 53 | ###PRIMARY KEY 54 | 添加主键约束 55 | ```sql 56 | ALTER TABLE tb_name ADD [CONSTRAIN[symbol]] PRIMARY KEY [index.type] (index_col_name,.....); 57 | ``` 58 | 删除主键约束 59 | ```sql 60 | ALTER TABLE tb_name DROP [index.type] PRIMARY KEY; 61 | ``` 62 | 不需要指定列名,因为每个表只有一个主键。 63 | 注意!只有一个主键并不意味着主键只有一列。 64 | ###UNIQUE 65 | 添加唯一约束 66 | ```sql 67 | ALTER TABLE tb_name ADD [index.type] unique(col_name); 68 | ``` 69 | 删除唯一约束 70 | ```sql 71 | ALTER TABLE tb_name DROP [index.type] unique(col_name); 72 | ``` 73 | ###DEFAULT 74 | ```sql 75 | ALTER TABLE tb_name ALTER [COLUMN] col_name {SET DEFAULT literal|DROP DEFAULT}; 76 | for example: 77 | ALTER TABLE users ALTER age SET DEFAULT 20; 78 | ``` 79 | ###FOREIGN KEY 80 | 添加外键约束 81 | ```sql 82 | ALTER TABLE tb_name ADD [CONSTRAIN[symbol]] FOREIGN KEY [index_name](index_col_name,...)reference_definition; 83 | for example: 84 | ALTER TABLE users add FOREIGN KEY (pid) REFERENCE provinces (id); 85 | ``` 86 | 删除外键约束 87 | ```sql 88 | ALTER TABLE tb_name DROP FOREIGN KEY fk_symbol; 89 | ``` 90 | -------------------------------------------------------------------------------- /SQL/加密函数.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guodongxiaren/MySQL-docs/a274ad111c1b04d2f2ed16e3949d89c2a6d650ef/SQL/加密函数.md -------------------------------------------------------------------------------- /SQL/多表更新.md: -------------------------------------------------------------------------------- 1 | 连接(多表更新) 2 | ================ 3 | ##多表更新 4 | ```mysql 5 | UPDATE table_references 6 | SET col_name1={expr1|DEFAULT} 7 | [,col_name2={expr2|DEFAULT}]... 8 | [WHERE where_condition] 9 | ``` 10 | 11 | ##CREATE...SELECT 12 | 创建数据表同时将查询结果写入到数据表 13 | ```mysql 14 | CREATE TABLE [IF NOT EXISTS]tb_name 15 | [(create_definetion,...)] 16 | select_statement 17 | ``` 18 | 比如: 19 | ```mysql 20 | CREATE TABLE tall ( 21 | tall_id SMALLINT UNSIGNED PRIMARY KEY AUTO_INCREMENT, 22 | num INT 23 | ) SELECT 身高 AS num FROM 24 | av 25 | GROUP BY 身高; 26 | ``` 27 | 创建新表tall,并从av表中选取身高字段插入到tall表的num字段。 28 | ##连接 29 | ###语法结构 30 | ```mysql 31 | table_reference 32 | {[INNER|CROSS] JOIN|{LELT|RIGHT}[OUTER] JOIN} 33 | table_reference 34 | ON conditional_expr 35 | ``` 36 | ON为条件。 37 | 三种连接,即: 38 | * 内连接 39 | * 左外连接 40 | * 右外连接 41 | 42 | ####内连接 43 | 显示左表及右表符合连接条件的记录(交集) 44 | ####左外连接 45 | 显示左表的全部记录及右表符合连接条件的记录 46 | ####右外连接 47 | 类别左外连接 48 | ###UPDATE..JOIN..SET 49 | 比如 50 | ```mysql 51 | UPDATE actor AS a 52 | INNER JOIN 53 | tall AS b ON a.tall = b.num 54 | SET 55 | a.tall = b.tall_id; 56 | ``` 57 | 依据实际情况,选择是否使用别名。(如果两个表中进行比较的字段名相同,则需要别名) 58 | 该语句完成了一个替换,将actor表中具体的身高数值,替换为tall表中身高的对应id。 59 | -------------------------------------------------------------------------------- /SQL/子查询.md: -------------------------------------------------------------------------------- 1 | 子查询 2 | ===== 3 | 子查询(Subquery)是指嵌套在查询内部,且必须始终出现在圆括号内。 4 | >外面的查询并非只是指的查找。 5 | 6 | ##可以包含的关键字或条件 7 | DISTINCT、GROUP BY、ORDER BY、LIMIT、函数等 8 | ##外层的查询可以是 9 | * SELECT 10 | * INSERT 11 | * UPDATE 12 | * SET 13 | * DO 14 | 15 | ##子查询分为三类 16 | ###使用比较运算符的子查询 17 | =,>,<,>=,<=,<>,!=,<=> 18 | 19 | ####语法结构 20 | operand comparison_operator {ANY|SOME|ALL} (subquery) 21 | 比如: 22 | ```mysql 23 | SELECT * FROM av WHERE 身高>=(SELECT AVG(身高) FROM av); 24 | ``` 25 | 字段名不加引号 26 | ####修饰比较运算符 27 | 使用ANY、SOME、ALL,ANY和SOME是等价的。 28 | 29 | ||ANY|ALL| 30 | |----|----|----| 31 | |>,>=|最小值|最大值| 32 | |<,<=|最大值|最小值| 33 | |=,<=>|任意值|| 34 | |<>,!=||任意值| 35 | 比如: 36 | ```mysql 37 | SELECT * FROM av WHERE 胸围>=ALL(SELECT 胸围 FROM av WHERE 身高<160); 38 | ``` 39 | 40 | ###使用[NOT]IN的子查询 41 | ####语法结构 42 | operand comparison_operator [NOT] IN (subquery) 43 | =ANY和IN等效 44 | !=ALL和NOT IN等效 45 | ###使用[NOT]EXISTS的子查询 46 | 如果子查询返回任何行,EXISTS将返回TRUE,否则返回FALSE。 47 | 该类子查询使用较少 48 | -------------------------------------------------------------------------------- /SQL/字符串函数.md: -------------------------------------------------------------------------------- 1 | 字符(串)函数 2 | ==== 3 | 函数可以在MySQL提示符中,直接用SELECT语句测试。 4 | 比如 **SELECT USER();** 5 | ##分类 6 | * 字符函数 7 | * 数值运算符与函数 8 | * 比较运算符与函数 9 | * 日期时间函数 10 | * 信息函数 11 | * 聚合函数 12 | * 加密函数 13 | 14 | ##字符(串)函数 15 | |名称|描述| 16 | |------|----- 17 | |CONCAT|字符串连接 18 | |CONCAT_WS|同上,但指定连接符 19 | |FORMAT|数字格式化 20 | |LOWER|转换成小写字母 21 | |UPPER|转换成大写字母 22 | |LEFT|获取左侧字符 23 | |RIGHT|获取右侧字符 24 | |LENGTH|获取长度 25 | |LTRIM|删除前导空格 26 | |RTRIM|删除后续空格 27 | |TRIM|删除前后空格 28 | |SUBSTRING|字符串截取 29 | |[NOT] LIKE|模式匹配 30 | |REPEAT|重复字符串 31 | |REPLACE|字符串替换 32 | 33 | ###CONCAT 34 | 参数个数不限,连接成一个字符串 35 | 已知test表的内如如下: 36 | ``` 37 | +----+------------+-----------+ 38 | | id | first_name | last_name | 39 | +----+------------+-----------+ 40 | | 1 | A | B | 41 | | 2 | C | D | 42 | | 3 | tom% | 123 | 43 | | 4 | NULL | 11 | 44 | | 5 | 11 | 22 | 45 | | 6 | AA | BB | 46 | | 7 | CC | DD | 47 | +----+------------+-----------+ 48 | ``` 49 | test表中有两个字段first_name,和last_name,调用连接函数之后: 50 | ```mysql 51 | SELECT CONCAT(first_name,last_name)AS full_name FROM test; 52 | 53 | +-----------+ 54 | | full_name | 55 | +-----------+ 56 | | AB | 57 | | CD | 58 | | tom%123 | 59 | | NULL | 60 | | 1122 | 61 | | AABB | 62 | | CCDD | 63 | +-----------+ 64 | ``` 65 | ###CONCAT_WS 66 | 参数至少有三个,第一参数为要连接字符串的分隔符,后面的都是待连接的字符串。 67 | ```mysql 68 | SELECT CONCAT_WS('-',1992,10,17); 69 | 70 | +---------------------------+ 71 | | CONCAT_WS('-',1992,10,17) | 72 | +---------------------------+ 73 | | 1992-10-17 | 74 | +---------------------------+ 75 | ``` 76 | ###FORMAT 77 | 将数字格式化为字符串。第二个参数为小数的位数。 78 | ```mysql 79 | SELECT FORMAT(12345.67,2); 80 | ``` 81 | 结果为千分位: 82 | ``` 83 | +--------------------+ 84 | | FORMAT(12345.67,2) | 85 | +--------------------+ 86 | | 12,345.67 | 87 | +--------------------+ 88 | ``` 89 | ###LOWER/UPPER 90 | 顾名思义,不再解释 91 | ###LEFT/RIGHT 92 | 获取左(右)侧第几个字符。 93 | 94 | SELECT LEFT('MySQL',2); 95 | ###LENGTH 96 | 获取字符串长度。SQL Server中是len函数。MySQL中没有len函数。 97 | ###LTRIM/RTRIM 98 | 删除前导/后续空格 99 | ###SUBSTRING 100 | 与其他语言中一样,截取子串的三个参数分别为: 101 | * 原字符串 102 | * 起始位置(注意下标从1算起;可以为负数,即从右数起) 103 | * 截取长度(缺省为截取到结尾) 104 | 105 | ###[NOT] LIKE 106 | SELECT FROM 'MySQL' LIKE 'M%'; 107 | 108 | 结果为1,即true。 109 | * %代表0个或多个字符。 110 | * _代表任意一个字符。 111 | 112 | > 关于转义 113 | 当要匹配的字符中含有特殊字符(比如%)时,需要转义。\,貌似\\也可以 114 | SELECT CONCAT(first_name,last_name)AS full_name FROM test WHERE first_name LIKE'%\%'; 115 | 116 | 也可以自己指定 117 | SELECT CONCAT(first_name,last_name)AS full_name FROM test WHERE first_name LIKE'%1%' ESCAPE '1'; 118 | 119 | ###TRIM 120 | 缺省可以删除前后空格,也可以删除指定的字符。 121 | ```mysql 122 | -- 删除??MySQL???前面的? 123 | SELECT TRIM(LEADING '?' FROM '??MySQL???'); 124 | -- 删除后面的? 125 | SELECT TRIM(TRAILING '?' FROM '??MySQL???'); 126 | -- 删除前后的? 127 | SELECT TRIM(BOTH '?' FROM '??MySQL???'); 128 | ``` 129 | ###REPEAT 130 | 重复某一字符串多少次 131 | ```mysql 132 | SELECT REPEAT('ab',2); 133 | ``` 134 | 结果是: 135 | ``` 136 | +----------------+ 137 | | REPEAT('ab',2) | 138 | +----------------+ 139 | | abab | 140 | +----------------+ 141 | 142 | ``` 143 | ###REPLACE 144 | ```MYSQL 145 | -- 去掉所有的? 146 | SELECT REPLACE('??MySQL','?',''); 147 | ``` 148 | 注意!替换的时候也可以一换多,多换一。 149 | -------------------------------------------------------------------------------- /SQL/存储过程.md: -------------------------------------------------------------------------------- 1 | 存储过程 2 | ======= 3 | 存储过程(Stored Procedure)是SQL语句和控制语句的预编译集合,以一个名称存储并作为一个单元处理。 4 | 其效率比函数更高。增强SQL语句的功能和灵活性。减少网络流量。 5 | 客户端重启,存储过程不会失效。定界符只对客户端有效,客户端重启,定界符失效。 6 | >数据库系统有三层结构:客户端、DBMS、服务端。我们的各种请求都是通过客户端发送给DBMS,DBMS将SQL语句编译成二进制,然后执行,接着缓存在DBMS中(再次执行时效率提高),接着发送给数据库服务端,然后服务端再返回数据给DBMS,DBMS再返回给客户端显示。 7 | 而存储过程,是将某些常用的请求,在DBMS中编译好二进制存储在DBMS中,以后再发送同样请求,就免去了编译的开销。 8 | 9 | 模块化编程,可以提高速度。但是可移植性不好。 10 | ##创建存储过程 11 | 创建之前必须先选择(USE)数据库。 12 | ```mysql 13 | CREATE 14 | [DEFINER = {user|CURRENT_USER}] 15 | PROCEDURE sp_name([proc_parameter[,...]]) 16 | [characteristic ...] routine_body 17 | 18 | proc_parameter: 19 | [IN|OUT|INOUT] param_name type 20 | ``` 21 | ###参数 22 | * IN,表示该参数的值必须在调用存储过程时指定 23 | * OUT,表示该参数的值可以被存储过程改变,并且可以被返回 24 | * INOUT,表示该参数的调用时指定,并且可以被改变和返回 25 | 26 | 可以这样理解,IN就是要传入的,值必须在调用时指定,不能返回(值传递),OUT是返回的(指针传递)。INOUT传入之后被返回的。 27 | ###过程体 28 | * 过程体由合法的SQL语句构成 29 | * 过程体是绝大部分SQL语句 30 | * 复合结构(超过两个SQL语句)使用BEGIN...END 31 | * 复合结构可以包含声明,循环,控制结构 32 | 33 | ##调用存储过程 34 | ```mysql 35 | CALL sp_name[()] 36 | ``` 37 | 如果存储过程没有参数,则调用的时候可以不加括号。 38 | ##删除存储过程 39 | 用DROP PROCDURE sp_name; 40 | 41 | -------------------------- 42 | 我们应该已经发现了,所有CREATE 创建的东西,都需要用DROP来删除。包括: 43 | 数据库、表、视图、触发器、函数、存储过程 44 | ##举例 45 | ```mysql 46 | delimiter // 47 | CREATE PROCEDURE 48 | removeuserbyid(IN u_id INT UNSIGNED) 49 | begin 50 | DELETE 51 | FROM users 52 | WHERE id = u_id;END// 53 | -- 调用 54 | CALL removeuserbyid(1)// 55 | ``` 56 | 注意参数的名字不能和字段名相同。 57 | ```mysql 58 | CREATE PROCEDURE 59 | remove2(IN p_id INT signed, 60 | OUT usernums INT UNSIGNED) 61 | begin 62 | DELETE 63 | FROM users 64 | WHERE id=p_id; 65 | 66 | SELECT count(id) 67 | FROM users 68 | INTO usernums; 69 | 70 | end// 71 | -- 调用 72 | CALL remove2(2,@nums)// 73 | -- 查看变量nums的值 74 | SELECT @nums// 75 | ``` 76 | 返回值存储在变量@nums中。 77 | ##修改存储过程 78 | ```mysql 79 | ALTER PROCEDURE sp_name[characteristic ...] 80 | COMMENT 'string' 81 | |{COUNTAINS SQL|NO SQL|READS SQL DATA|MODIFIES SQL DATA} 82 | |SQL SECURITY{DEFINER|INVOKER}| 83 | ``` 84 | ##与函数对比 85 | 存储过程实现的功能更复杂一些;而函数的针对性更强。 86 | 时间经常用存储过程对表作操作。 87 | 存储过程可以用多个返回值。 88 | 存储过程独立出现。 89 | 函数出现在其他SQL语句内部。 90 | -------------------------------------------------------------------------------- /SQL/插入记录.md: -------------------------------------------------------------------------------- 1 | 插入记录 2 | ======= 3 | 共有三种Insert语句。 4 | ##INSERT 5 | ```sql 6 | INSERT [INTO] tb_name [(col_name,.....)] {VALUE|VALUES} ({expr|DEFAULT},...) (...),... 7 | ``` 8 | * values是标准SQL关键字,value是MySQL自己的。 9 | * 插入语句可以一次性插入多条记录。 10 | * 值可以是: 11 | * 函数 12 | * 数学表达式 13 | * 等 14 | 15 | ###默认值 16 | 在创建数据表的时候可以设置DEFAUTL。 17 | ```sql 18 | CREATE TABLE users( 19 | id SAMLLINT UNSIGNED PRIMARY KEY AUTO_INCREMENT, 20 | username SAMLLINT VARCHAR(20) NOT NULL, 21 | password SAMLLINT VARCHAR(20) NOT NULL, 22 | age TINYINT UNSIGNED NOT NULL DEFAULT 10, 23 | sex BOOLEAN 24 | ); 25 | ``` 26 | INSERT的时候如果为自动编号的字段(比如上表中主键id)赋值的话,可写作NULL,或DEFAULT就会采用默认值。 27 | 如果字段设置了DEFAULT(比如上表中age),那么值直接写DEFAULT就行,注意此时,不能为NULL。例如: 28 | ```sql 29 | INSERT users VALUES(NULL,'TOM','123',DEFAULT,1); 30 | ``` 31 | ##INSERT...SET 32 | ```sql 33 | INSERT [INTO] tb_name SET col_name={expr|DEFAULT},... 34 | ``` 35 | 采用了[子查询](子查询.md)。例如,上表中插入: 36 | ```sql 37 | INSERT users SET username='Ben',password='456'; 38 | ``` 39 | 因为id,和age都有默认值,所以可以不写。而sex允许为空,也可以不写。 40 | ##INSERT...SELECT* 41 | 将查找的结果写入记录中。 42 | ```sql 43 | INSERT test(username) SELECT username FROM users WHERE age >=30; 44 | ``` 45 | -------------------------------------------------------------------------------- /SQL/数值运算与比较运算.md: -------------------------------------------------------------------------------- 1 | 数值运算 2 | ------- 3 | |名称|描述| 4 | |---|---- 5 | |CEIL()|进一取整 6 | |DIV|整数除法 7 | |FLOOR()|舍一取整 8 | |MOD|模运算 9 | |POWER()|幂运算 10 | |ROUND()|四舍五入 11 | |TRUNCARE()|数字截取 12 | ###CEIL/FLOOR/ROUND 13 | 前两者为对应操作。一个向上取整,一个向下取整。第三个ROUND为四舍五入。 14 | ###DIV/MOD 15 | 两者并非函数,而是 **运算符**。 16 | ```mysql 17 | SELECT 5 DIV 2; 18 | SELECT 7 MOD 3; 19 | ``` 20 | MOD与%等价,就是模运算,与别不同的是,MySQL中支持浮点数取模。 21 | ###POWER 22 | 幂运算 23 | ###TRUNCARE 24 | 所谓的数字截取,就是对数字逐位的截断。 25 | ```mysql 26 | SELECT TRUNCATE(125.123, 1); 27 | SELECT TRUNCATE(125.123, 0); 28 | SELECT TRUNCATE(125.123, - 1); 29 | ``` 30 | 运算的结果分别为:125.1、125.0,120 31 | 比较运算符与函数 32 | ------------- 33 | |名称|描述| 34 | |---|---- 35 | |[NOT] BETWEEN...AND...|[不]在范围内 36 | |[NOT] IN()|[不]在列出的值范围内 37 | |IS [NOT] NULL|[不]为空 38 | -------------------------------------------------------------------------------- /SQL/数据库操作.md: -------------------------------------------------------------------------------- 1 | 数据库操作 2 | ======= 3 | ##创建数据库 4 | ```mysql 5 | CREATE {DATABASE|SCHEMA} [IF NOT EXISTS] db_name [DEFAULT] CHARCTER SET [=] charset_name; 6 | ``` 7 | >注意设置字符集的时候,utf-8要写作utf8。 8 | 9 | ##修改数据库 10 | ```mysql 11 | ALTER {DATABASE|SCHEMA} db_name [DEFAUTL] CHARCTER SET [=] charset_name; 12 | ``` 13 | ###修改数据库编码格式 14 | SET NAMES GBK; 15 | GBK也可以是其他编码格式。但这只是修改你客户端显示的编码格式。服务端并不变化。 16 | **修改配置文件来改服务端编码** 17 | 打开/etc/my.cnf文件 18 | 在[mysqld]条目下:增加 19 | ``` 20 | character_set_server=utf8 21 | init_connect='SET NAMES utf8' 22 | ``` 23 | 有时在数据库创建完成后,编码格式是无法修改的。只能删掉重新建。 24 | ##删除数据库 25 | ```mysql 26 | DROP {DATABASE|SCHEMA} [IF EXISTS] db_name; 27 | ``` 28 | -------------------------------------------------------------------------------- /SQL/日期时间函数.md: -------------------------------------------------------------------------------- 1 | 日期时间函数 2 | -------- 3 | |名称|描述| 4 | |----|---- 5 | |NOW()|当前日期和时间 6 | |CURDATE()|当前日期 7 | |CURTIME()|当前时间 8 | |DATE_ADD()|日期变化 9 | |DATEDIFF()|日期差值 10 | |DATE_FORMATE()|日期格式化 11 | ###NOW/CURDATE/CURTIME 12 | 可以把NOW看作是CURDATE和CURTIME的综合 13 | ###DATE_ADD 14 | 实现日志的增减,加为正数,减为负数 15 | ```mysql 16 | SELECT DATE_ADD(CURDATE(),INTERVAL 3 WEEK); 17 | ``` 18 | WEEK,也可以是DAY,YEAR 19 | 与之相对的还有一个DATE_SUB函数。 20 | ###DATEDIFF 21 | 获取两个日期之间的差值,左边减去右边,值为天数。 22 | ```MYSQL 23 | SELECT DATEDIFF('2014-10-11','2014-09-06'); 24 | ``` 25 | ###DATE_FORMAT() 26 | 日期格式化为其他形式,比如: 27 | ```mysql 28 | SELECT DATE_FORMAT('2014-11-01','%m/%d/%Y'); 29 | ``` 30 | 结果为: 31 | 11/01/2014 32 | 如果是小写的y,则格式化为11/01/14 33 | 34 | -------------------------------------------------------------------------------- /SQL/更新记录.md: -------------------------------------------------------------------------------- 1 | 更新记录分为: 2 | * 单表更新 3 | * 多表更新(要涉及连接) 4 | 5 | 更新记录(单表更新) 6 | ================ 7 | ```mysql 8 | UPDATE [LOW_PRIORITY] [IGNORE] tb_reference 9 | SET col_name1={expr|DEFAULT} [,col_name2={expr|DEFAULT}]... 10 | [WHERE where_condition] 11 | ``` 12 | 不写where会更新全部的记录。 13 | 14 | 删除记录 15 | ======= 16 | 同样分为: 17 | * 单表删除 18 | * 多表删除 19 | 20 | ```mysql 21 | DELETE FROM tb_name [WHERE where_condition]; 22 | ``` 23 | 没有where部分则会删除全部记录。 24 | 25 | -------------------------------------------------------------------------------- /SQL/权限管理.md: -------------------------------------------------------------------------------- 1 | 权限管理 2 | ========= 3 | |权限范围|可用权限 4 | |----|---- 5 | |表权限|`Select`, `Insert`, `Update`, `Delete`, `Create`, `Drop`, `Grant`, `References`, `Index`, `Alter` 6 | |列权限|`Select`, `Insert`, `Update`,`References` 7 | |过程权限|`Execute`, `Alter Routine`, `Grant` 8 | 9 | ##授权 10 | ```sql 11 | GRANT SELECT ON *.* TO jelly@'%' 12 | //给一个用户(jelly)分配全部的操作权限 13 | GRANT ALL PRIVILEGES ON *.* TO jelly@'%' 14 | ``` 15 | %就是前面我们提到过的通配符,可以匹配0到n个字符。这里指的是该用户所登录的任何主机。 16 | 17 | ##取消授权 18 | 语法: 19 | ```sql 20 | REVOKE privilege ON databasename.tablename FROM 'username'@'host'; 21 | ``` 22 | 例如: 23 | ```sql 24 | REVOKE SELECT ON test.user FROM 'jelly'@'%'; 25 | REVOKE ALL ON *.* FROM 'jelly'@'%'; 26 | ``` 27 | >**GRANT**和**REVOKE**对于用户而言,一个是**TO**,一个是**FROM** 28 | 29 | ##查看授权 30 | 例如: 31 | ```sql 32 | SHOW GRANTS FOR 'jelly'@'%'; 33 | ``` 34 | ##刷新权限 35 | ```sql 36 | FLUSH PRIVILEGES 37 | ``` 38 | 偶尔会出现,修改了操作系统表的权限,却没有及时更新的情况。可以用上述命令刷新。 -------------------------------------------------------------------------------- /SQL/查询.md: -------------------------------------------------------------------------------- 1 | 查询语句 2 | ======= 3 | 查询就是SELECT语句 4 | ##数学计算 5 | SELECT 3*9 6 | 7 | ##查询记录 8 | ```sql 9 | SELECT select_expr [,select_expr ...] 10 | [ 11 | FROM table_references 12 | [WHERE where_condition] 13 | [GROUP BY {col_name|position} [ASC|DESC],...] 14 | [HAVING where_condition] 15 | [ORDER BY {col_name|expr|position} [ASC|DESC],...] 16 | [LIMIT {[offset,] row_count|row_count OFFSET offset}] 17 | ] 18 | ``` 19 | ###别名 20 | ```sql 21 | SELECT id AS userId,username AS uname FROM users; 22 | ``` 23 | 查询出来的列名,就变成了别名。AS其实可以省略,但可能会出现问题。 24 | ```sql 25 | SELECT id username FROM users; 26 | ``` 27 | 这样会将username视作id的别名。 28 | ###分组GROUP BY 29 | ```sql 30 | [GROUP BY {col_name|position} [ASC|DESC],...] 31 | ``` 32 | ASC和DESC分别是升序(缺省)和降序。 33 | 看一个脚本: 34 | ```sql 35 | SELECT * FROM users; 36 | SELECT sex FROM users GROUP BY sex; 37 | ``` 38 | 两条语句的执行结果分别为: 39 | ![](http://img.my.csdn.net/uploads/201410/11/1413025525_3910.png) 40 | 41 | ![](http://img.my.csdn.net/uploads/201410/11/1413025525_8278.png) 42 | 也可以使用编号代替字段名,但是这样不鼓励。比如上面的分组语句可以写成: 43 | ```sql 44 | SELECT sex FROM users GROUP BY 1; 45 | ``` 46 | 后面的数字1,值得是在SELECT选取的字段中的顺序。这里只选了一个字段,当然为1。 47 | ####HAVING 48 | 与GROUP BY分组联用。只对部分记录做分组操作。有两种用法,比如: 49 | ```sql 50 | SELECT sex,age FROM users GROUP BY sex HAVING age > 35; 51 | SELECT sex FROM users GROUP BY sex HAVING count(id) >=2; 52 | ``` 53 | * 第一种,注意后面的HAVING的字段必须在前面SELECT部分出现才行。 54 | * 第二种,在HAVING后面使用*聚合函数*,前面无需出现相应字段。 55 | 56 | !!!Having放在group by后面 57 | ###排序ORDER BY 58 | ```sql 59 | [ORDER BY {col_name|expr|position} [ASC|DESC],...] 60 | ``` 61 | 比如: 62 | ```sql 63 | SELECT * FROM users ORDER BY id DESC; 64 | ``` 65 | 可以排序多个字段,如果第一个字段能排出结果,就不会用到第2个字段。比如: 66 | ```sql 67 | SELECT * FROM users ORDER BY id ,id DESC; 68 | ``` 69 | 因为年龄age有相同的,继续排序就要用到id的降序。 70 | ###限制返回记录的数量LIMIT 71 | LIMIT有两种语法结构,第一种比较常见。 72 | ```sql 73 | [LIMIT {[offset,] row_count|row_count OFFSET offset}] 74 | ``` 75 | 起始位置,偏移量 76 | ```sql 77 | SELECT * FROM users ; 78 | SELECT * FROM users LIMIT 3,2; 79 | SELECT * FROM users LIMIT 2; 80 | ``` 81 | 3,2:表示从第3条开始返回,返回两条记录。注意记录从0开始编号,即结果集中的从第0条开始。 82 | 如果LIMIT后面只有一个参数,认作是偏移量,起始位置缺省为0。 83 | ![](http://img.my.csdn.net/uploads/201410/11/1413025525_3910.png) 84 | ![](http://img.my.csdn.net/uploads/201410/11/1413028833_7155.png) 85 | ![](http://img.my.csdn.net/uploads/201410/11/1413028833_9032.png) 86 | 87 | ###合并查询结果UNION 88 | 在多条查询语句之间,使用`UNION`关键字会何必所有查询结果。 89 | 默认会去掉重复行,如果不想去掉重复行,请使用`UNION ALL` 90 | 需要注意的是,要联合的查询结果必须有相同的列数(列名可以不同) 91 | >去重效率比不去重效率低 92 | -------------------------------------------------------------------------------- /SQL/用户管理.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guodongxiaren/MySQL-docs/a274ad111c1b04d2f2ed16e3949d89c2a6d650ef/SQL/用户管理.md -------------------------------------------------------------------------------- /SQL/索引.md: -------------------------------------------------------------------------------- 1 | 索引 2 | ==== 3 | 索引能提高查询效率,但是查询效率和修改效率一直是一个矛盾。 4 | ##普通索引 5 | ```mysql 6 | -- 单独创建,colname为列名 7 | CREATE INDEX indexname ON tablename(colname(length)); 8 | -- 也可以在修改表的时候创建 9 | ALTER TABLE table_name ADD INDEX [index_name] (column_list) 10 | -- 创建表的时候指定 11 | CREATE TABLE mytable( 12 | ID INT NOT NULL, 13 | username VARCHAR(16) NOT NULL, 14 | INDEX [indexname] (username(length) 15 | ); 16 | ``` 17 | ##唯一索引 18 | 索引列必须唯一,但可以为NULL,不能有多个NULL。 19 | ```mysql 20 | -- 单独创建 21 | CREATE UNIQUE INDEX indexname ON tablename(colname(length)); 22 | -- 也可以在修改表的时候创建 23 | ALTER TABLE table_name ADD UNIQUE [index_name] (column_list) 24 | -- 创建表的时候指定 25 | CREATE TABLE mytable( 26 | ID INT NOT NULL, 27 | username VARCHAR(16) NOT NULL, 28 | UNIQUE INDEX [indexname] (username(length) 29 | ); 30 | ``` 31 | ##主键索引 32 | 就是之前所说过的主键。不能使用`CREATE`语句单独创建。 33 | ```mysql 34 | -- 可以在修改表的时候创建 35 | ALTER TABLE tablename ADD PRIMARY KEY (column_list); 36 | -- 在表级定义主键 37 | CREATE TABLE mytable( 38 | ID INT NOT NULL, 39 | username VARCHAR(16) NOT NULL, 40 | PRIMARY KEY(ID) 41 | ); 42 | -- 在列级定义主键 43 | CREATE TABLE mytable( 44 | ID INT NOT NULL PRIMARY KEY, 45 | username VARCHAR(16) NOT NULL 46 | ); 47 | ``` 48 | 由上可知,有两种主键定义方法。但是两者不尽相同。在列级定义主键**这样是无法指定多个字段做主键的**,这中情况下只能在表级定义主键 49 | ###索引组织表 50 | InnoDB引擎中,表都是根据主键顺序组织存放的。称之为`索引组织表`。 51 | 在没有显示地声明主键的情况下,InnoDB按照如下方式选择或创建主键: 52 | * 如果存在`非空`的`唯一约束`,则将该列视为主键 53 | * 如果不存在,则自动创建一个6字节大小的指针 54 | 55 | 如果表中有多个非空的唯一索引,那么InnoDB选择第一个定义的非空索引。这里依据的顺序是索引定义的顺序,而不是建表时列的顺序。 56 | ###_rowid 57 | 在主键为单个列的时候,我们可以使用_rowid来查看主键的值。 58 | ```mysql 59 | -- 比如: 60 | SELECT *,_rowid FROM test; 61 | ``` 62 | ##全文索引 63 | 只有InnodB引擎支持 64 | -------------------------------------------------------------------------------- /SQL/约束.md: -------------------------------------------------------------------------------- 1 | 约束 2 | ------- 3 | ###分类 4 | 根据列的数目分为: 5 | * 列级约束 6 | * 对一个数据列建立的约束,称为列级约束 7 | * NOT NULL和DEFAULT只有列级约束 8 | * 其他三个有表级约束 9 | * 表级约束 10 | * 对多个数据列建立的约束,称为表级约束 11 | 12 | 列级约束可以在列定义时声明,也可以在列定义后声明。 13 | 表级约束只能在列定义后声明。 14 | 15 | 根据功能分为: 16 | 17 | |代码|描述| 18 | |------|-------| 19 | |NOT NULL| 非空约束 20 | |PRIMARY KEY|主键约束 21 | |UNIQUE|唯一约束 22 | |DEFAULT|默认约束 23 | |FOREGIN KEY|外键约束 24 | ###注意 25 | - 父表和子表具有相同的存储引擎(--InnoDB--) 26 | - 外键列和参照列必须具有相似的数据类型 27 | - 其中数字的长度或是否有符号必须相同 28 | - 字符的长度可以不同 29 | - 外键列和参照列必须创建 *索引*,如果外键列不存在索引,MySQL会自动帮其创建,但是不会自动帮参照列创建 30 | 31 | >父表:具有参照列的是父表,比如省份与人中的省份。 32 | 子表:具有外键列的是子表,比如人 33 | 34 | ###外键约束的参照操作 35 | - CASEADE //更新(删除)父表(中的行),子表也随之更新 36 | - SET NULL 37 | - RESTRICT 38 | - NO ACTION //标准的SQL关键字,功能与MySQL中的RESTRICT相同。 39 | -------------------------------------------------------------------------------- /SQL/聚合函数.md: -------------------------------------------------------------------------------- 1 | 聚合函数 2 | ------------ 3 | |名称|描述| 4 | |------|------- 5 | |AVG|平均值 6 | |COUNT|计数 7 | |MAX|最大值 8 | |MIN|最小值 9 | |SUM|求和 10 | ###注意 11 | * 聚合函数只有一个返回值! 12 | * 不能直接用SELECT 加函数名的形式来调用,必须针对字段! 13 | * 优先级 14 | * 聚合函数优先级小于WHERE语句,不能用来WHERE后面。 15 | * 聚合函数优先级大于HAVING,可以用在HAVING后面。 16 | 17 | ##COUNT 18 | - COUNT(*)统计null 19 | - COUNT(字段)不统计null 20 | - COUNT(1)可统计 21 | -------------------------------------------------------------------------------- /SQL/自定义函数.md: -------------------------------------------------------------------------------- 1 | 自定义函数 2 | =========== 3 | UDF(User-defined function) 4 | ##创建自定义函数 5 | ```mysql 6 | CREATE FUCNTION function_name 7 | RETURNS 8 | {STRING|INTEGER|REAL|DECIMAL} 9 | RETURN 10 | routine_body 11 | ``` 12 | ##函数体 13 | 上面的routine_body指代函数体。其构成: 14 | * 函数体由合法的SQL语句构成 15 | * 函数体可以是简单的SELECT或INSERT语句 16 | * 函数体如果为符合结构则使用BEGIN...END语句 17 | * 符合结构可以包含声明,循环,控制结构 18 | 19 | ##举例 20 | `来源慕课网` 21 | ```mysql 22 | -- 无参数 23 | CREATE function f() 24 | RETURNS VARCHAR(30) 25 | RETURN Date_format(Now(), '%Y年%m月%d日 %H点:%i分:%s秒'); 26 | ``` 27 | ```mysql 28 | -- 带参数 29 | CREATE function f2(num1 SMALLINT UNSIGNED, 30 | num2 SMALLINT UNSIGNED) 31 | RETURNS FLOAT(10, 2) UNSIGNED 32 | RETURN ( num1 + num2 ) / 2; 33 | ``` 34 | ``` 35 | -- 复合结构的函数体 36 | DELIMITER // 37 | CREATE function 38 | adduser(username VARCHAR(20)) returns INT UNSIGNED 39 | BEGIN 40 | INSERT test 41 | ( 42 | username 43 | ) 44 | VALUES 45 | ( 46 | username 47 | ); 48 | 49 | RETURN Last_insert_id(); 50 | END// 51 | ``` 52 | 三个要点: 53 | * 首先因为函数体内有分号,所以我们要修改定界符,避免函数中途停止。使用DELIMITER指定新的定界符为//。 54 | * 然后,因为函数体内有多条SQL语句,所以我们要用BEGIN...END包裹。 55 | * RETURN在BEGIN...END结构内部。并且必须有RETURN。默认情况下,RETURN后面的语句会在屏幕上打印出来。 56 | 57 | ##删除函数 58 | ```mysql 59 | DROP FUCNTION [IF EXISTS] function_name; 60 | ``` 61 | 一次只能删除一个函数。 62 | -------------------------------------------------------------------------------- /SQL/表基本操作.md: -------------------------------------------------------------------------------- 1 | 表基本操作 2 | ====== 3 | ##查看表 4 | ```sql 5 | SHOW TABLES [FROM db_name] [LIKE 'pattern'|WHEAR expr]; 6 | ``` 7 | ##查看列(表的组织结构) 8 | ```sql 9 | SHOW COLUMNS FROM tb_name; 10 | DESC tb_name; 11 | ``` 12 | 以上两条语句都可以。 13 | ##查看表的内容 14 | ```sql 15 | SELECT * FROM tb_name; 16 | ``` 17 | ##插入数据 18 | ```sql 19 | INSERT [INTO] tb_name [(col_name,...)] VALUES(val,...); 20 | ``` 21 | 如果不指明任何字段名,那么插入的数据必须要包含所有的字段。 22 | -------------------------------------------------------------------------------- /SQL优化/IN操作.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guodongxiaren/MySQL-docs/a274ad111c1b04d2f2ed16e3949d89c2a6d650ef/SQL优化/IN操作.md -------------------------------------------------------------------------------- /SQL优化/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guodongxiaren/MySQL-docs/a274ad111c1b04d2f2ed16e3949d89c2a6d650ef/SQL优化/README.md -------------------------------------------------------------------------------- /接口编程/C++/01 连接数据库.md: -------------------------------------------------------------------------------- 1 | 连接数据库 2 | =========== 3 | ## 头文件 4 | ```cpp 5 | #include // 驱动类 6 | #include // 连接类 7 | ``` 8 | ## 驱动 9 | 加载驱动是每个mysql接口编程的基础。 10 | ```cpp 11 | sql::mysql::MySQL_Driver *driver; 12 | 13 | driver = sql::mysql::get_mysql_driver_instance(); 14 | ``` 15 | > error: ‘get_mysql_driver_instance’ is not a member of ‘sql::mysql::MySQL_Driver’ 16 | >>在官方教程中,代码是这样:`dirver = sql::mysql::MySQL_Driver::get_mysql_driver_instance();` 17 | 其实该函数不在MySQL_Driver类中。请注意。如果按教程中写了,就会出现上述错误。 18 | 19 | ## 连接数据库 20 | ```cpp 21 | sql::Connection *con; 22 | 23 | con = driver->connect("tcp://127.0.0.1:3306", "root", "password"); 24 | ``` 25 | 三个参数分别是mysql的ip和端口,用户名以及密码。 26 | ### Connection类 27 | 28 | |主要成员函数|返回值|说明 29 | |---|----|--- 30 | |setSchema()|void|切换到指定数据库(参数为数据库名) 31 | |isValid()|bool|连接是否有效 32 | |reconnect()|bool|如果连接中断则重连 33 | 34 | ## Demo 35 | ```cpp 36 | #include 37 | 38 | #include 39 | #include 40 | using namespace std; 41 | using namespace sql; 42 | int main() 43 | { 44 | mysql::MySQL_Driver *driver; 45 | Connection *con; 46 | 47 | driver = mysql::get_mysql_driver_instance(); 48 | if (driver) 49 | { 50 | cout<<"dirver ok"<connect("tcp://127.0.0.1:3306", "root", "123456"); 54 | if (con) 55 | { 56 | cout<<"conn ok"< 7 | ``` 8 | ## 类 9 | 是一个接口类。只包含纯虚函数。 10 | ```cpp 11 | sql::Statement *stmt; 12 | // 创建对象 13 | stmt = con->createStatement(); 14 | ``` 15 | ### 成员函数 16 | ```cpp 17 | virtual bool excute(const sql::SQLString& sql) = 0; 18 | ``` 19 | ## Demo 20 | ```cpp 21 | #include 22 | 23 | #include 24 | #include 25 | #include 26 | using namespace std; 27 | using namespace sql; 28 | int main() 29 | { 30 | mysql::MySQL_Driver *driver; 31 | Connection *con; 32 | 33 | driver = mysql::get_mysql_driver_instance(); 34 | if (!driver) 35 | { 36 | cout<<"dirver error"<connect("tcp://127.0.0.1:3306", "root", "123456"); 41 | if (!con) 42 | { 43 | cout<<"conn error"<createStatement(); 49 | if (!stmt) 50 | { 51 | cout<<"stmt error"<execute("USE test"); // 选择数据库 56 | stmt->execute("DROP TABLE IF EXISTS test"); // 如果表已存在,则删除 57 | stmt->execute("CREATE TABLE test(id INT, label CHAR(1))"); // 创建表 58 | stmt->execute("INSERT INTO test(id, label) VALUES(1, 'a')"); //插入数据 59 | 60 | delete stmt; 61 | delete con; 62 | } 63 | ``` 64 | -------------------------------------------------------------------------------- /接口编程/C++/03 PreparedStatement.md: -------------------------------------------------------------------------------- 1 | PreparedStatement 2 | ================= 3 | 是一种特殊的“语句”类。 4 | - Statement类执行的语句只能是静态的字符串 5 | - PreparedStatement类执行的语句可以含有变量(采用占位符思想实现) 6 | 7 | ## 头文件 8 | ```cpp 9 | #include 10 | ``` 11 | ## 类 12 | ```cpp 13 | PreparedStatement *pstmt; 14 | // 创建对象 15 | pstmt = con->prepareStatement("INSERT INTO test(id, label) VALUES(?, ?)"); 16 | ``` 17 | 通过Connector对象的prepareStatement函数来创建该类对象。其参数是一个含有占位符(**?**)的SQL语句。 18 | ### 填充占位符 19 | ```cpp 20 | pstmt->setInt(1, 2); // 给第一个占位符填充数字2 21 | pstmt->setString(2, "b"); // 给第二个占位符填充字符串"b" 22 | ``` 23 | ### 执行SQL 24 | ```cpp 25 | pstmt->execute(); 26 | ``` 27 | 28 | ## Demo 29 | ```cpp 30 | #include 31 | 32 | #include 33 | #include 34 | #include 35 | using namespace std; 36 | using namespace sql; 37 | int main() 38 | { 39 | mysql::MySQL_Driver *driver; 40 | Connection *con; 41 | 42 | driver = mysql::get_mysql_driver_instance(); 43 | if (!driver) 44 | { 45 | cout<<"dirver error"<connect("tcp://127.0.0.1:3306", "root", "123456"); 50 | if (!con) 51 | { 52 | cout<<"conn error"<setSchema("test"); 57 | PreparedStatement *pstmt; 58 | pstmt = con->prepareStatement("INSERT INTO test(id, label) VALUES(?, ?)"); 59 | if (!pstmt) 60 | { 61 | cout<<"prepared stmt error"<setInt(1, 2); 65 | pstmt->setString(2, "b"); 66 | pstmt->execute(); 67 | 68 | delete pstmt; 69 | delete con; 70 | } 71 | ``` 72 | -------------------------------------------------------------------------------- /接口编程/C++/04 ResultSet.md: -------------------------------------------------------------------------------- 1 | ResultSet 2 | ========= 3 | SQL语句返回的结果集 4 | ## 头文件 5 | ```cpp 6 | #include 7 | ``` 8 | ## 创建对象 9 | 由`sql::Statement::executeQuery()`和`sql::PreparedStatement::executeQuery()`返回。 10 | 比如: 11 | ``` 12 | sql::Connection *con; 13 | sql::Statement *stmt; 14 | sql::ResultSet *res; 15 | // ... 16 | con->setSchema("test"); 17 | // ... 18 | stmt = con->createStatement(); 19 | res = stmt->executeQuery("SELECT id, label FROM test"); 20 | ``` 21 | ## 成员函数 22 | ### next 23 | 返回bool类型,用于**逐行**遍历结果集。 24 | 25 | 结果集内部有**游标**,标记着当前行。游标起始位置为第一行,每次执行完next函数,游标都会移动到下一行。 26 | ## getXXX 27 | |函数|返回值|说明 28 | |-----|-----|----- 29 | |getInt|int32_t|返回当前行某一列的值作为整型 30 | |getString|SQLString|返回当前行某一列值作为字符串 31 | |getUInt|uint32_t|......32位无符号整型 32 | |getInt64|int64_t|......64位有符号整型 33 | |getUInt64|uint64_t|......64位无符号整型 34 | |getBoolean|bool|......bool类型 35 | |getBlob|std::istream|.......二进制类型 36 | 37 | **getXXX**是一系列函数,用于取出当前行某一列值。**XXX**表示数据类型。 38 | 39 | 该系类函数有两个重载: 40 | - 可以用整型作为参数,表示取第几列的值。 41 | - 也可以使用字符串作为参数,取出对应列名的值。 42 | 43 | 比如 44 | ``` 45 | while (res->next()) 46 | { 47 | cout << "id = "<getInt(1)<<";label = "<getString("label")<setAutoCommit(false); 9 | ``` 10 | 11 | ## 提交事务 12 | ```c 13 | con->commit(); 14 | ``` 15 | 16 | ## 事务回滚 17 | ```c 18 | con->rollback(); 19 | ``` 20 | -------------------------------------------------------------------------------- /接口编程/C++/README.md: -------------------------------------------------------------------------------- 1 | MySQL Connector/C++接口编程 2 | ============================ 3 | ## 头文件路径 4 | ``` 5 | include/ 6 | ├── cppconn 7 | │ ├── build_config.h 8 | │ ├── config.h 9 | │ ├── connection.h 10 | │ ├── datatype.h 11 | │ ├── driver.h 12 | │ ├── exception.h 13 | │ ├── metadata.h 14 | │ ├── parameter_metadata.h 15 | │ ├── prepared_statement.h 16 | │ ├── resultset.h 17 | │ ├── resultset_metadata.h 18 | │ ├── sqlstring.h 19 | │ ├── statement.h 20 | │ ├── variant.h 21 | │ ├── version_info.h 22 | │ └── warning.h 23 | ├── mysql_connection.h 24 | ├── mysql_driver.h 25 | └── mysql_error.h 26 | ``` 27 | ## 编译环境 28 | 需要存在boost库。 29 | 一种可能g++的编译选项: 30 | 31 | ```makefile 32 | CFLAGS = -I/usr/local/mysql/include \ 33 | -I/usr/local/boost/include \ 34 | -L/usr/local/boost/lib \ 35 | -L/usr/local/mysql/lib \ 36 | -Wl,-rpath=/usr/local/mysql/lib \ 37 | -lmysqlcppconn \ 38 | ``` 39 | 如果mysql的库路径没有被编辑在**/etc/ld.so.conf.d/**目录中(要有root权限,并用ldconfig命令刷新)的话, 40 | 则需要用**-Wl,-rpath**选项指定。 41 | -------------------------------------------------------------------------------- /高级概念/MySQL命令.md: -------------------------------------------------------------------------------- 1 | MYSQL命令 2 | ======= 3 | ##登陆命令 4 | mysql -u用户名 -p密码 5 | 用户名和-u选项之间可以有空格,但是密码和-p选项之间必须无空格。但是这样密码会是明文。你可以在键入-p之后,回车再输入密码,就是密文。 6 | ###常用选项 7 | 8 | |缩写|全写|描述 9 | |----|---|--- 10 | |-h|--host|主机 11 | |-p|--password|密码 12 | |-P|--port|端口 13 | |-V|--version|版本信息 14 | |-u|--user|用户 15 | ||--prompt|修改提示符 16 | 17 | ####--prompt 18 | --prompt 支持几个转义词组 19 | * \h 主机名 20 | * \D 完整日期 21 | * \d 当前数据库 22 | * \u 当前用户 23 | 24 | ##登陆之后 25 | ###退出 26 | * exit 27 | * quit 28 | * \q 29 | 30 | 都能退出mysql,系统显示Bye。 31 | ###帮助 32 | 键入`help`或`\h`。 33 | ###显示信息 34 | select: 35 | * version(); 版本信息 36 | * now(); 当前时间 37 | * user(); 用户@主机名 38 | 39 | ###使用系统命令 40 | **\!** 后加shell命令可以在mysql中执行shell命令。 41 | >gdb使用shell加命令来执行shell命令。 42 | -------------------------------------------------------------------------------- /高级概念/README.md: -------------------------------------------------------------------------------- 1 | 高级概念 2 | ============ 3 | * [存储引擎](存储引擎.md) 4 | * [备份还原](备份还原.md) 5 | * 日志体系 6 | * 集群,高可用 7 | * 主从复制 8 | * 双机互援 9 | * 索引的实现:B+,Hash 10 | -------------------------------------------------------------------------------- /高级概念/备份还原.md: -------------------------------------------------------------------------------- 1 | 备份 2 | ==== 3 | 如果是MyISAM的数据库引擎,那么直接复制相应的数据库文件即可。 4 | 如果是InnoDB则需要利用命令。这也是更为一般的普适方法。 5 | 6 | 利用MySQL提供的工具———— **mysqldump** 7 | 8 | ##mysqldump 9 | 10 | mysqldump -uroot -p database_name [table_name1,...] >pathname.sql 11 | 12 | ###备份数据库 13 | 使用时需指定用户名,并使用-p选项,再回车后键入密码。实际上是利用的[重定向](#重定向)来生成一个sql脚本文件。 14 | 该文件中包含各个sql语句。 15 | 16 | 重定向符号后面的是sql文件的路径。Linux请使用`/`来表示目录结构。Windows可以用`\` 也可以用 `/`。 17 | 比如: 18 | ####Linux 19 | 20 | mysqldump -uroot -p world >/home/jelly/config/world.sql 21 | ####Windows 22 | 23 | mysqldump -uroot -p world >d:/config/world.sql 24 | mysqldump -uroot -p world >d:\config\world.sql** 25 | 26 | ###备份部分表 27 | 如果不想备份整个数据库,而是像备份某个表,那么在数据库后面指定表的名称。 28 | 29 | 还原 30 | ==== 31 | 执行已备份的sql脚本文件。有两种方案: 32 | ##已连接数据库时 33 | 登录mysql命令行,使用source命令(与mysqldump不同,source不是独立工具,而是MySQL内部命令)来执行sql脚本。 34 | 需要先创建一个数据库,然后切换到给数据库,再执行该命令。 35 | 36 | mysql> source d:/tool/world.sql 37 | 38 | ##未连接数据库时 39 | 直接在shell的命令行执行: 40 | 41 | mysql -uroot -p < /home/jelly/config/world.sql 42 | 43 | -------------------------------------------------------------------------------- /高级概念/存储引擎.md: -------------------------------------------------------------------------------- 1 | 存储引擎 2 | ======== 3 | 存储引擎是基于表的,不是基于数据库的。 4 | 5 | |功能|MyISAM|InnoDB|Memory|Archive| 6 | |------|:----:|:----:|:----:|:----: 7 | |存储限制|256T|64T |有 |无 8 | |事务安全|- |支持|- |- 9 | |索引支持|支持|支持|支持|- 10 | |锁颗粒 |表锁|行锁|表锁|行锁 11 | |数据压缩|支持|- |- |支持 12 | |外键 |- |支持|- |- 13 | 14 | 以上是常用引擎,另外还有其他存储引擎。 15 | --------------------------------------------------------------------------------