{"id":20603636,"url":"https://github.com/kayw-geek/mysql-note","last_synced_at":"2025-09-09T18:51:12.490Z","repository":{"id":118926102,"uuid":"371316317","full_name":"kayw-geek/MySQL-Note","owner":"kayw-geek","description":"MySQL 必知必会 学习笔记","archived":false,"fork":false,"pushed_at":"2021-07-01T03:58:16.000Z","size":39,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-17T02:12:10.406Z","etag":null,"topics":["mysql","notebook","sql","study-notes"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kayw-geek.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-05-27T09:21:50.000Z","updated_at":"2021-07-01T03:58:19.000Z","dependencies_parsed_at":null,"dependency_job_id":"2c63c34a-c432-4280-9bf1-d6fa48e5462d","html_url":"https://github.com/kayw-geek/MySQL-Note","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kayw-geek%2FMySQL-Note","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kayw-geek%2FMySQL-Note/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kayw-geek%2FMySQL-Note/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kayw-geek%2FMySQL-Note/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kayw-geek","download_url":"https://codeload.github.com/kayw-geek/MySQL-Note/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":242249149,"owners_count":20096803,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["mysql","notebook","sql","study-notes"],"created_at":"2024-11-16T09:18:00.875Z","updated_at":"2025-03-06T16:41:09.675Z","avatar_url":"https://github.com/kayw-geek.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# MySQL笔记\n持续更新中 ~ 本书一共30章 目前学习到 21章 还有9章就学习完了，继续学下一本\n\n[MySQL笔记](#mysql笔记)\n- [查询去除重复的结果集](#查询去除重复的结果集)\n  - [限制结果集](#限制结果集)\n    - [使用完全限定的表名查询](#使用完全限定的表名查询)\n    - [排序查询结果集](#排序查询结果集)\n      - [指定排序方向关键字 desc acs](#指定排序方向关键字-desc-acs)\n      - [order by 与 limit](#order-by-与-limit)\n    - [过滤数据](#过滤数据)\n      - [where 子句操作符](#where-子句操作符)\n    - [空值检查](#空值检查)\n    - [组合where 子句](#组合where-子句)\n      - [逻辑操作符 and or\\`](#逻辑操作符-and-or)\n      - [操作符 in](#操作符-in)\n      - [操作符 not](#操作符-not)\n      - [like操作符](#like操作符)\n      - [\\_操作符](#_操作符)\n    - [用正则表达式进行查询](#用正则表达式进行查询)\n      - [基本字符匹配](#基本字符匹配)\n      - [进行 or 匹配](#进行-or-匹配)\n      - [匹配范围](#匹配范围)\n      - [匹配特殊字符](#匹配特殊字符)\n      - [匹配多个实例](#匹配多个实例)\n      - [定位符](#定位符)\n    - [创建计算字段](#创建计算字段)\n      - [计算字段](#计算字段)\n      - [去除空格](#去除空格)\n      - [使用别名](#使用别名)\n      - [执行算数计算](#执行算数计算)\n    - [使用数据处理函数](#使用数据处理函数)\n      - [文本处理函数](#文本处理函数)\n      - [日期时间处理函数](#日期时间处理函数)\n      - [数值处理函数](#数值处理函数)\n    - [汇总数据](#汇总数据)\n      - [聚集函数](#聚集函数)\n      - [组合聚集函数](#组合聚集函数)\n    - [分组数据](#分组数据)\n      - [创建分组](#创建分组)\n      - [过滤分组](#过滤分组)\n      - [子句顺序](#子句顺序)\n    - [使用子查询](#使用子查询)\n      - [子查询](#子查询)\n      - [作为计算字段使用子查询](#作为计算字段使用子查询)\n    - [联结表](#联结表)\n      - [内部联结](#内部联结)\n      - [左联结](#左联结)\n      - [右联结](#右联结)\n    - [创建高级联结](#创建高级联结)\n      - [使用表别名](#使用表别名)\n      - [自联结](#自联结)\n      - [使用带聚集函数的联结](#使用带聚集函数的联结)\n    - [组合查询/复合查询](#组合查询复合查询)\n      - [使用union](#使用union)\n    - [全文本搜索](#全文本搜索)\n      - [要点](#要点)\n      - [进行全文搜索](#进行全文搜索)\n      - [使用查询扩展](#使用查询扩展)\n      - [布尔文本搜索](#布尔文本搜索)\n      - [布尔全文搜索操作符](#布尔全文搜索操作符)\n      - [注意事项](#注意事项)\n    - [插入数据](#插入数据)\n      - [数据插入](#数据插入)\n      - [插入多个行](#插入多个行)\n      - [将查询出的数据插入到另一个表中](#将查询出的数据插入到另一个表中)\n    - [更新和删除数据](#更新和删除数据)\n      - [更新数据](#更新数据)\n      - [update 使用子查询](#update-使用子查询)\n      - [删除数据](#删除数据)\n    - [创建和操控表](#创建和操控表)\n      - [创建表](#创建表)\n      - [not null](#not-null)\n      - [主键](#主键)\n      - [auto\\_increment](#auto_increment)\n      - [last\\_insert\\_id](#last_insert_id)\n      - [指定默认值](#指定默认值)\n      - [引擎类型](#引擎类型)\n      - [更新表](#更新表)\n      - [删除表](#删除表)\n      - [重命表](#重命表)\n    - [使用视图](#使用视图)\n      - [视图](#视图)\n      - [使用视图](#使用视图-1)\n      - [使用视图重新格式化检索出的数据](#使用视图重新格式化检索出的数据)\n      - [使用视图过滤不想要的数据](#使用视图过滤不想要的数据)\n      - [使用视图与计算字段](#使用视图与计算字段)\n      - [更新视图](#更新视图)\n    - [使用存储过程](#使用存储过程)\n      - [存储过程](#存储过程)\n      - [执行存储过程](#执行存储过程)\n      - [创建存储过程](#创建存储过程)\n      - [删除存储过程](#删除存储过程)\n      - [使用参数](#使用参数)\n      - [建立只能存储过程](#建立只能存储过程)\n      - [检查存储过程](#检查存储过程)\n\n#### 查询去除重复的结果集\n\n`使用DISTINCT关键字`\n\n```mysql\nSELECT DISTINCT vend_id FROM products;\n```\n\n#### 限制结果集\n\n`使用LIMIT关键字`\n\n```mysql\nSELECT prod_name FROM products limit 5;\n#只查询5条\nselect prod_name from products limit 3,5;\n# 从查询结果集的第3条开始取出 5条；\nselect prod_name from products offset 3 limit 5;\n#等同于上面的查询语句\n```\n\n#### 使用完全限定的表名查询\n\n```mysql\nselect products.prod_name from chasing.products;\n# 查询 从chasing数据库中的产品表中查询产品表中的产品名称字段\n```\n\n#### 排序查询结果集\n\n`使用子句 order by`\n\n```mysql\n  select prod_name from products order by prod_name;\n  #从产品表中查询所有产品名称并对产品名称字段排序 默认排序规则为升序 （小的在前面）\n  select prod_name,prod_price,prod_id from products order by prod_price,prod_name;\n  #同时对产品价格和产品名称进行排序\n  #会对产品价格进行升序排序，如果出现相同的价格时，才会对产品名称进行排序，如果产品价格都是唯一的，那么不会对产品名称进行排序\n```\n\n##### `指定排序方向关键字 desc acs` \n\n```mysql\n  #升序排序 ACS : A-Z 默认排序规则\n  #降序排序 DESC : Z-A\n  select prod_name from products order by prod_name desc;\n  #对产品名称进行降序排序\n  select prod_name,prod_price from products order by prod_price desc ,prod_name;\n  #对产品价格使用降序排序，产品名称使用升序排序\n  #desc 关键字 只作用于 它前面的 字段生效 \n```\n\n##### `order by 与 limit`\n\n```mysql\n  select prod_price from products order by prod_price desc limit 1;\n  # 查询产品表中最贵的一个商品\n  # 子句的顺序\n  # from --- order by desc --- limit --- offset \n  \n```\n\n#### 过滤数据\n\n`使用子句 where`\n\n```mysql\nselect prod_name,prod_price from products where prod_price = 2.50;\n#查询产品价格等于2.50 的全部商品\n# 子句的顺序\n# select --- from --- where --- order by desc --- limit --- offset \n```\n\n##### `where 子句操作符`\n\n| 操 作 符 | 说 明              |\n| -------- | ------------------ |\n| =        | 等于               |\n| \u003c \u003e      | 不等于             |\n| !=       | 不等于             |\n| \u003c        | 小于               |\n| \u003e        | 大于               |\n| \u003c=       | 小于等于           |\n| =\u003e       | 大于等于           |\n| between  | 在指定的俩个值之间 |\n|          |                    |\n\n```mysql\nselect prod_name from products where product_name = 'dory';\n# 查询结果 不区分大小写 ，结果集可能出现 Dory DORY dory\nselect prod_price from products where product_price \u003c\u003e 10;\n#查询产品价格不等于10 的所有产品\nselect prod_price form products where between product_price 4 and 10;\n#查询产品价格在4 - 10 之间的所有产品\n```\n\n#### 空值检查\n\n`使用子句 is null`\n\n```mysql\nselect prod_name from products where prod_price is null;\n#查询所有价格为空值得产品名称\n# 空值是只该字段为空 未赋值过 无默认值 ，它与 0 空字符串 空格 不同\n```\n\n#### 组合where 子句\n\n##### 逻辑操作符 and or`\n\n```mysql\nselect prod_id,prod_price,prod_name from products where vend_id = 1003 and prod_price \u003c= 10;\n# 查询产品表 vend_id 等于 1003 并且 prod_price 小于等于10的全部商品；\n\n#如果要查询 多个并且条件 和一个或者条件的语句如何查询？\nselect prid_name,prod_price from products where (vend_id = 1002 or vend_id = 1003) and prod_price \u003e= 10;\n# 查询商品制造号 为 1002 或者 1003 的 并且 价格要小于等于10 的全部产品\n#（）计算次序高于 and 和 or\n```\n\n##### 操作符 in\n\n```mysql\nselect prod_name,prod_price from products where vend_id in (1002,1003) order by prod_name;\n# in 最大的优点是可以包含其他select 语句 动态建立where子句\n```\n\n##### 操作符 not \n\n```mysql\n# where 子句中的not 操作符只有一个功能 否定它之后所跟的任何条件\nselect prod_name,prod_price from products where vend_id not in (1002,1003) order by prod_name;\n# 查询 产品制造号不为 1002 和 1003 的所有产品 并使用降序排序产品名称\n\n```\n\n##### like操作符\n\n```mysql\nselect prod_id,prod_name from products where prod_name like 'jet%';\n# 必须指定like 关键字 'jet%' 表示查询匹配jet开头的全部产品\nselect prod_id,prod_name from products where prod_name like '%jet%';\n# 表示查询包含jet的字符串的全部产品\nselect prod_id,prod_name from products where prod_name like 's%e';\n# 表示查询开头为s 结尾为e的结果 包括se\n# % 不能匹配 NULL 值\n\n```\n\n##### _操作符\n\n```mysql\nselect prod_id,prod_name from products where prod_name like 's_e';\n#_只能匹配单个字符 如 sse sxe\n#% 能匹配0-n 个字符 \n```\n\n#### 用正则表达式进行查询\n\n##### 基本字符匹配\n\n```mysql\nselect prod_name from products where prod_name regexp '.000' order by prod_name;\n# 使用关键字 regexp \n#regexp 后面跟的为正则表达式规则\n# .表示匹配任意字符 查询的结果可能为2000 x000\n# MySQL 中的正则表达式匹配不区分大小写\nselect prod_name from products where prod_name regexp binary 'Jetpack .000';\n#如果要精确匹配大小写 使用binary 关键字\n```\n\n##### 进行 or 匹配\n\n```mysql\nselect prod_name from products where prod_name regexp '100|200|300' order by prod_name;\n# 查询产品名称包含 100 或 包含200 或 包含300 的所有产品名称\n```\n\n##### 匹配范围\n\n```mysql\nselect prod_name from products where prod_name regexp '[a-z] ton';\n# 匹配结果如 a ton b ton\n```\n\n##### 匹配特殊字符\n\n```mysql\nselect prod_name from products where prod_name regexp '\\\\.' order by prod_name;\n#匹配产品名称包含.的结果 \n#\\\\ 为转义字符\n# \\\\\\ 为匹配 字符 \\\n```\n\n##### 匹配多个实例\n\n```mysql\nselect prod_name from products where prod_name regexp '\\\\([0-9 sticks?\\\\])' order by prod_name;\n# [0-9] 匹配任意数字\n# sticks?  ?的意思是前一个字符出现1次或0次 所以就是 stick 也可以 sticks 也可以\n# 可能匹配到的结果为 1 stick 、 0 sticks\n\nselect prod_name from products where prod_name regexp '[[:digit:]]{4}' order by prod_name;\n\n#[:digit:] 匹配任意数字\n#{4}要求前面的字符出现4次\n#可能匹配到的结果为 1000 2313 2314\n```\n\n##### 定位符\n\n```mysql\nselect prod_name from products where prod_name regexp '^[0-9\\\\.]' order by prod_name;\n# 匹配以任意数字加.开头的所有产品名称\n# 可能匹配的结果为 1.23 0.xx\n```\n\n#### 创建计算字段\n\n##### 计算字段\n\n```mysql\nselect Concat(vend_name,'(',vend_country,')') from vendors order by vend_name;\n# concat 拼接函数\n# 把查询结果中的 vend_name 字段和 vend_country 拼接起来\n# concat函数 可以拼接多个字符串 使用, 分割要拼接的字符串\n\n```\n\n##### 去除空格\n\n```mysql\nselect Concat(RTrim(vend_name),'(',RTrim(vend_country),')') from vendors order by vend_name;\n#RTrim 函数为去除字符串右边的多余空格\n#LTrim 函数为去除字符串左边的多余空格\n#Trim 函数为去除字符串俩边的多余空格\n```\n\n##### 使用别名\n\n```mysql\nselect Concat(RTrim(vend_name),'(',RTrim(vend_country),')') as vend_title from vendors order by vend_name;\n# 上面语句将处理后的字段 定义别名为 vend_title \n```\n\n##### 执行算数计算\n\n```mysql\nselect prod_id,quantity,item_price,quantity*item_price as expanded_price from orderitems where order_num = 20005;\n#上面语句将数据库中数量字段和单价字段乘法运算后 别名为 expanded_price 字段\n```\n\n#### 使用数据处理函数\n\n##### 文本处理函数\n\n```mysql\nselect vend_name,Upper(vend_name) as vend_name_upcase from vendors order by vend_name;\n# Upper() 转换为大写\n# Left() 返回串左边的字符\n# Length() 返回串的长度\n# Locate() 找出串的一个子串\n# Lower() 转换为小写\n# Right() 返回串右边的字符\n# Soundex() 返回串的 SOUNDEX值 匹配所有发音类似于指定字符串的结果\n# SubString() 返回子串的字符\n\n```\n\n##### 日期时间处理函数\n\n```mysql\nselect cust_id,order_num from orders where Date(order_date) = '2005-09-01';\n# 查询oder_date 日期等于 2005-09-01 的结果\n# order_data 的数据类型应该是Datetime 类型\n# 这样可以查询出 这一天的订单 就算是储存结果为 2005-09-01 12:30:22 也可以查询出来\n\nselect cust_id,order_num from orders where Date(order_date) between '2005-09-01' and '2005-09-30';\n# 匹配日期范围内的数据\n\nselect cust_id,order_num from orders where Year(order_date) = 2005 and Month(order_date) = 9;\n# 匹配 2005年 9月分的数据\n```\n\n##### 数值处理函数\n\n```mysql\n# Abs() 绝对值\n# Mod() 取余\n# Rand() 随机数\n```\n\n#### 汇总数据\n\n##### 聚集函数\n\n```mysql\n# avg()\nselect avg(prod_price) as avg_price from products where vend_id = 1993;\n# 查询id为1993这个产品的价格平均值\n# avg()函数忽略列值为null的行 空的会自动忽略不会被计算\n\n# count()\nselect count(*) as num_cust from customers;\n# 查询客户表的总条数\nselect count(cust_email) as num_cust from customers;\n# 查询客户表中 邮箱不为null的总条数\n# 如果使用count(*) 不会忽略null行\n\n# max()\nselect max(prod_price) as max_price from products;\n# 查询价格最贵的商品\nselect max(id) as max_row from products;\n# 查询该表一共有多少行有效数据\n# max() 忽略null值行\n\n# min()\nselect min(prod_price) as min_price from products;\n# 查询价格最便宜的商品\n# min() 函数忽略null值行\n\n# sum()\nselect sum(quantity) as items_ordered from orderitems where order_num = 20005;\n# 查询orderitems 表中订单号为20005 的这条 一共有多少个商品\nselect sum(quantity * item_price) as total_price from orderitems where order_num = 2005;\n# 查询订单号2005 的订单总价格\n# sum() 函数忽略null值行\n```\n\n##### 组合聚集函数\n\n```mysql\nselect count(*) as num_items,min(prod_price) as price_min,max(prod_price) as price_max,avg(prod_price) as price_avg from products;\n# 查询产品表中的 总行数 价格最便宜的商品 价格最贵的商品 平均价格\n# 使用函数直接计算 会比查询后在程序中计算会快得多\n```\n\n#### 分组数据\n\n##### 创建分组\n\n```mysql\nselect vend_id,count(*) as num_prods from products group by vend_id;\n# 分组查询每个供应商制造的产品数量\n# 如果分组中有null值，则null将作为一个分组返回，如果有多行null值，它们将分为一组\n# group by 子句必须出现在where子句后面 order by 子句之前\n# GROUP BY子句中列出的每个列都必须是检索列或有效的表达式\n#（但不能是聚集函数）。如果在SELECT中使用表达式，则必须在\n# GROUP BY子句中指定相同的表达式。不能使用别名。\n```\n\n##### 过滤分组\n\n```mysql\nselect cust_id,count(*) as orders from orders group by cust_id having count(*) \u003e=2;\nselect cust_id,count(*) as orders from orders group by cust_id having orders \u003e=2;\n# 查询每个下单的顾客的 订单数量 并且订单数量大于等于 2\n# having 和 where一样 区别就是 where过滤分组前的数据 having过滤分组后结果\n\nselect count(*) as order_num,user_id from orders where order_status \u003e= 10 group by user_id  having order_num \u003e= 10 LIMIT 100;\n# 查询 每个下单顾客 下单数量大于10单的 并且订单状态大于10的  前100条\n\nselect count(*) as order_num,user_id from orders where order_status \u003e= 10 group by user_id  having order_num \u003e= 10 order by order_num LIMIT 100;\n# 查询 每个下单顾客 下单数量大于10单的 并且订单状态大于10的  前100条 并升序排列\n\nselect sum(goods_number * goods_price) as total,order_id from order_goods group by order_id  having total \u003e= 1000 order by total desc LIMIT 100;\n# 查询 每个订单的 总价的订单号 并且总价大于等于 1000 并且按总价排降序 的前一百条\n```\n\n##### 子句顺序\n\n```\nselect --- from --- where --- group by --- having --- order by --- limit\n\n```\n\n#### 使用子查询\n\n##### 子查询\n\n```mysql\nselect email from user where id in();\nselect user_id from orders where id in();\nselect order_id from order_goods where goods_id = 8;\n\nselect email from user where id in(select user_id from orders where id in(select order_id from order_goods where goods_id = 8));\n# 查询购买了产品id为8的的顾客姓名\n```\n\n##### 作为计算字段使用子查询\n\n```mysql\nselect user_id,count(*) as order_num from orders  group by user_id order by order_num desc limit 100;\n# 查询每个客户的订单总数\n\nselect email,(select count(*) from orders where orders.user_id = user.id) as order_num from user order by order_num desc;\n# 查询每个客户的订单总数 和 邮箱\n```\n\n#### 联结表\n\n##### 内部联结\n\n```mysql\nselect orders.id,user.email from orders inner join user on user.id = orders.user_id;\n# 使用内联查询下过订单的用户邮箱\n# 只查询出符合关联条件的数据\n```\n\n##### 左联结\n\n```mysql\nselect orders.id,user.email from orders left join user on user.id = orders.user_id;\n# 左表为主表  查询主表的所有数据 如果 被关联的表符合关联条件就查出关联数据 没有就为空\n# 也就是查询orders 表的全部数据 不管 user 是否有数据\n```\n\n##### 右联结\n\n```mysql\nselect orders.id,user.email from orders right join user on user.id = orders.user_id;\n# 右表为被关联的表  查询右表的所有数据 如果 被关联的表符合关联条件就查出关联数据 没有就为空\n# 也就是查询user 表的全部数据 不管 order 是否有数据\n```\n\n#### 创建高级联结\n\n##### 使用表别名\n\n```mysql\nselect o.id,u.email from orders as o left join user as u on u.id = o.user_id;\n```\n\n##### 自联结\n\n```mysql\n# 想查询产品id等于 8的产品的供应商 查出该供应商产的全部产品\n# 子查询方法\nselect prod_id,prod_name from products where vend_id = (select vend_id from products where prod_id = 8);\n# 自联结方法\nselect prod_id,prod_name from products as p1,products as p2 where p1.vend_id = p2.vend_id and where p1.prod_id = 8;\n```\n\n##### 使用带聚集函数的联结\n\n```mysql\nselect orders.id,user.email,count(orders.id) as order_num from orders inner join user on user.id = orders.user_id group by user.email order by  order_num desc;\n# 使用聚集函数 + 内部联结 查询 每个下单用户的下单次数 并降序排列\n```\n\n#### 组合查询/复合查询\n\n##### 使用union\n\n```mysql\nselect order_sn from orders  where order_status \u003e= 15;\nselect order_sn from orders  where user_id  = 19;\n# 想查询订单状态大于 15 附加 下单用户id 等于 19的订单（不考虑价格）\nselect order_sn from orders  where order_status \u003e= 15 union select orders_sn from orders  where user_id = 19;\n#UNION必须由两条或两条以上的SELECT语句组成，语句之间用关\n#键字UNION分隔（因此，如果组合4条SELECT语句，将要使用3个\n#UNION关键字）。\n\n# union 自动去除重复结果\n# union all \n```\n\n#### 全文本搜索\n\n##### 要点\n\n```mysql\nMyISAM 数据库引擎支持全文本搜索\nLIKE 和 正则匹配的搜索模式 性能极低\n建表时需要指定全文查询的关键字段或之后指定 使用子句 FULLTEXT 将会对被指定的字段进行索引创建；MySQL会在新增、更改、删除行后自动维护该字段索引\n```\n\n##### 进行全文搜索\n\n```mysql\nselect note_text from productnones where match(note_text) against('rabbit');\n# match 指定索引字段\n# against 指定要搜索的关键词\n# 查找结果默认不区分大小写\n# 使用全文搜索会根据查询数据的权重排序\n```\n\n##### 使用查询扩展\n\n```mysql\n# 作用：扩大查询范围即使查询的行数据中不包含指定关键词\n# MySQL 工作流程\n# 1.找出与搜索条件匹配的所有行\n# 2.检查这些匹配行并选择所有有用的词\n# 3.再次执行第一步 单搜索条件 增加了 第二部获取的关键词\nselect note_text from productnotes where match(note_text) against('anvils' with query expansion);\n# 解析第二步 \n# 假如搜索词为 php 搜索出的匹配行中有这样一条数据 i love php \n# 那么搜索结果可能会将\"i love php\"结果中的 love 作为扩展词\n```\n\n##### 布尔文本搜索\n\n```mysql\nselect note_text from productnotes where match(note_text) against('heavy' in boolean mode);\n# 优点不用设置 fulltext 索引\n# 缺点非常慢\n\n# 特殊规则查询\nselect note_text from productnotes where match(note_text) against('heavy -rope*' in boolean mode);\n# 查询所有包含heavy 的结果 但处理以 “rope” 开头的 \n```\n\n##### 布尔全文搜索操作符\n\n```mysql\n# + 包含，关键词必须存在\n# - 排除，关键词不允许出现\n# \u003e 包含，增加权重\n# \u003c 包含，减少权重\n#（）表达式使用子表达式时\n# ~ 取消一个词的排序值\n# * 词尾的排序值\n# \"\" 定义一个短语 eg: \"i love you\" 则必须包含i love you 才会被查询出来\n```\n\n##### 注意事项\n\n```mysql\n# 短词会被自动忽略 不会建立到索引中 短词长度为 \u003c= 3\n# 系统关键词自动忽略 \n# 50% 如果一个词出现频率高于50% 则会忽略\n# 如果表中的行数少于3行 则不会查询出任何结果 因为 50% 原则\n# 忽略词中的单引号 如 don't 会被索引为 dont\n# 日语和汉语 不能恰当的返回全文本搜索结果\n# 只有MyISAM 引擎支持全文搜索\n```\n\n#### 插入数据\n\n##### 数据插入\n\n```mysql\ninsert into customers values(null,'weikai','100','angeles','ca','90046','usa');\n# 仅指定要插入的表名 和 依次要插入的字段的值 \ninsert into customers(cust_name,cust_address,cust_city,cust_state) values('weikai','beijing','beijing','cn');\n# 完整插入语句 指定插入的表名 和字段名 和字段值\n\n```\n\n##### 插入多个行\n\n```mysql\ninsert into customers(cust_name,cust_address,cust_city,cust_state) values('weikai','beijing','beijing','cn');\ninsert into customers(cust_name,cust_address,cust_city,cust_state) values('weikai','beijing','beijing','cn');\ninsert into customers(cust_name,cust_address,cust_city,cust_state) values('weikai','beijing','beijing','cn');\n#或者\ninsert into customers values(null,'weikai','100','angeles','ca','90046','usa'),(null,'weikai','100','angeles','ca','90046','usa'),\n(null,'weikai','100','angeles','ca','90046','usa');\n\n# for 循环插入数据可以使用一次插入多行 这样性能会比循环插入性能提高很多\n```\n\n##### 将查询出的数据插入到另一个表中\n\n```mysql\ninsert into customers(cust_id,cust_contact,cust_email,cust_name) select cust_id,cust_contact,cust_email,cust_name from custnew;\n# 查询custnew表中的所有行 并 将查询结果插入到customers 表中\n# select 语句也可以使用where 来过滤查询结果\n```\n\n#### 更新和删除数据\n\n##### 更新数据\n\n```mysql\nupdate  customers set cust_email = 'weikaiii@sina.cn' where cust_id='123';\n# 修改用户表 用户id为123 的 邮箱为 weikaiii@sina.cn\n# 关键词 update 表名 set 字段名 where 条件\n\nupdate customers set cust_email = 'weikaiii@sina.cn',cust_name = 'weikai' where cust_id = '123';\n# 同时修改满足条件的多个字段值\n```\n\n##### update 使用子查询\n\n```mysql\nupdate user u set email=(select email from admin where u.username = admin.username);\n# 查询admin 表中用户名与user 表中一样的数据 修改他们的email\n# 注意俩个字段的类型\n```\n\n##### 删除数据\n\n```mysql\ndelete from customers where cust_id = 10005;\n# 删除 customers 表 当cust_id 等于 10005的数据；\n# 关键词 delete from 表名 where 条件\n```\n\n#### 创建和操控表\n\n##### 创建表\n\n```mysql\ncreate table customers \n(\n\tcust_id int not null auto_increment,\n    cust_name char(50) not null,\n    cust_address char(50) null,\n    primary key (cust_id)\n) engine=Innodb;\n\n\n# 关键词 create table 表名字 if not exists # 仅仅再表不存在时候创建防止报错\n#（\n#   字段名 字段类型 字段约束 ...\n#        ...\n#    primary key (主键字段名)\n# ）engine=mysql 引擎\n\n```\n\n##### not null\n\n```mysql\n# 字段约束 not null 约束该字段值不能为空 如果赋予空值时会产生异常错误\n```\n\n##### 主键\n\n```mysql\n# 主键必须唯一\n# 关键词 primary key (字段名)\n# 主键自动应用规则 not null \n```\n\n##### auto_increment\n\n```mysql\n# 自动增量 当插入新数据时自动维护字段值\n# 关键词 auto_increment\n# 每个表中只允许一个字段设置auto_increment 并且该字段必须被索引\n```\n\n##### last_insert_id\n\n```mysql\n# 该函数可获取最新插入的这条数据的 auto_increment 字段值\n# select last_insert_id();\n```\n\n##### 指定默认值\n\n```mysql\n# 作用： 给指定字段当没被赋值时一个指定的默认值\n# 关键字 default 123;\n# 默认值仅支持 常量\n```\n\n##### 引擎类型\n\n```mysql\n# 关键词 engine= 引擎名\n# InnoDB 可靠的事务处理引擎 不支持全文搜索\n# MyISAM 高性能 支持全文搜索 不支持事务处理\n# MEMORY 功能等同于MyISAM 数据储存再内存中 不在硬盘 速度快\n# 外键不支持跨引擎\n```\n\n##### 更新表\n\n```mysql\n#关键词 alter table 表名 条件\nalter table users add phone integer(11);\n# 给已有的表 users 增加一个字段phone \nalter table users drop column phone;\n# 给已有的表 users 删除一个字段 phone\nalter table orderitems add constraint fk_orderitems_orders foreign key(order_num) references orders (order_num)\n# 给表 orderitems 添加一个 外键 名为 fk_orderitems_orders 外键字段为 order_num 关联 orders 表 字段为order_num\n```\n\n##### 删除表\n\n```mysql\ndrop table users;\n```\n\n##### 重命表\n\n```mysql\nrename table users to users;\n```\n\n#### 使用视图\n\n##### 视图\n\n```mysql\n# 视图是一个虚拟的表 它不包含任何数据和表结构 它只包含了一个SQL 语句\n# 作用： 重用SQL 语句\n# \t\t简化复杂的SQL语句（把复杂的SQL语句封装成视图）\n# 性能：性能不好\n# 规则：视图名必须唯一\n#\t   视图可以使用Order By 如果 select中也存在order by 视图中的将忽略\n#\t   视图可以和表一起使用 可以写一条联结表和视图的查询\n```\n\n##### 使用视图\n\n```mysql\ncreate view productcustomers as select cust_name,cust_contact,prod_id,from customers,order,orderitems where customers.cust_id = orders.cust_id and orderitems.order_num = orders.order_num;\n# 创建一个名字为 productcustomers 的视图\n# 这个视图联结了三个表 关联了 订单 订单商品 客户三个表之间的联系\n\nselect * from productcustomers; \n# 使用视图查询订购过产品的所有用户\nselect * from productcustomers where prod_id = 'tnt';\n# 查询订购过tnt 产品的用户信息\n# 原理： productcustomers = create view productcustomers as select cust_name,cust_contact,prod_id,from customers,order,orderitems where customers.cust_id = orders.cust_id and orderitems.order_num = orders.order_num + where prod_id = 'tnt'；\n```\n\n##### 使用视图重新格式化检索出的数据\n\n```mysql\ncreate view vendorlocations as select concat(rtrim(vend_name),'(',rtrim(vend_country),')') as vend_title from vendors order by vend_name;\n# 创建一个视图 查询处理后的供应商名字\nselect * from vendorlocations;\n```\n\n##### 使用视图过滤不想要的数据\n\n```mysql\ncreate view customeremaillist as select sust_id,cust_name,cust_email from customers where cust_email is not null;\n# 创建一个视图名字为 customeremaillist 查询用户信息过滤邮箱为空的数据\nselect * from customeremaillist;\n# 如果视图定义中存在where 使用视图时也使用了where 那么查询结果将自动组合 并且关系\n```\n\n##### 使用视图与计算字段\n\n```mysql\ncreate view orderitemsexpanded as select order_num,prod_id,quantity,item_price,quantity*item_price as expanded_price from orderitems;\n# 创建视图名字为 orderitemsexpanded 查询订单商品信息 并计算商品总价格 别名为 expanded_price\nselect * from orderitemsexpanded where order_num = 20006;\n# 查询订单商品表订单号为 20006 的订单商品信息和 商品总价格\n```\n\n##### 更新视图\n\n```mysql\n# 规则: 如果使用视图进行数据的更新或删除则 视图语句中不能包含以下操作\n# group by \n# having\n# 联结\n# 子查询\n# 并且\n# 聚集函数\n# distinct\n# 导出列\n```\n\n#### 使用存储过程\n\n##### 存储过程\n\n```mysql\n# 可以把存储过程理解成 一组查询语句 批文件\n# 作用：\n# 封装一组SQL语句 简化复杂的操作流程\n# 保证数据完整性\n# 提高性能 存储过程比单独执行sql语句要快\n```\n\n##### 执行存储过程\n\n```mysql\ncall productpricing(@pricelow,@pricehigh,@priceaverage);\n```\n\n##### 创建存储过程\n\n```mysql\ncreate procedure productpricing() \nbegin \nselect avg(prod_price) as priceaverage from products;\nend;\n# 分析\n# create procedure 存储过程名()\n# begin\n# sql 语句\n# end;\n\n# 临时修改分隔符命令 delimiter 分隔符\ncall productpricing();\n#调用存储过程\n```\n\n##### 删除存储过程\n\n```mysql\ndrop procedure if exists productpricing;\n# 只需要指定存储过程名字 不需要()\n```\n\n##### 使用参数\n\n```mysql\ncreate procedure productpricing(\n\tout pl decimal(8,2),\n    out ph decimal(8,2),\n    out pa decimal(8,2)\n)\nbegin\n\tselect min(prod_price)\n\tinto pl from products;\n\tselect max(prod_price)\n\tinto ph from products;\n\tselect avg(prod_price)\n\tinto pa from products;\nend;\n\n# 分析\n# 创建存储过程 名字为 productpricing 并设置三个形参\n# 定义返回参数 pl ph pa  指定接受参数的变量类型为 decimal \n# 使用计算函数指定要查询的字段 并使用 into 调用 变量 pl \n\n\ncall productpricing(@pricelow,@pricehigh,@priceaverage);\n# 分析\n# 传递参数需要使用@开头\n# 调用结果不显示任何数据 但是返回 可以显示的变量\nselect @pricehigh,@pricelow;\n# 返回结果为 @pricehigh 55.00 @pricelow 2.50\n\ncreate procedure ordertotal(in onumber int, out ototal decimal(8,2))\nbegin\n\tselect sum(item_price*quantity)\n\tfrom orderitems\n\twhere order_num = onumber\n\tinto ototal;\nend;\n# 分析 创建一个名为 ordertotal 的存储过程 指定传参 onumber int 类型, 返回参数 ototal decimal 类型\n# 查询订单商品 商品价格总和 条件为 订单号等于传入的订单号\n# into 存储查询结果到变量 ototal;\n\ncall ordertotal(20006,@total);\n# 分析 调用存储过程 ordertotal 并传递参数20006 设置返回参数为@total\nselect @total;\n# 查询结果 @total 149.22\n\n```\n\n##### 建立只能存储过程\n\n```mysql\ncreate procedure ordertotal(\n\tin onumber int,\n    in taxable boolean,\n    out ototal decimal(8,2)\n) comment 'xxxxxxx'\nbegin \n-- xcxxxx\ndeclare total decimal(8,2);\ndeclare taxrate int default 6;\n\nselect sum(item_price*quantity)\nfrom orderitems\nwhere order_num = onumber\ninto total;\nif taxable then\n\tselect total+(total/100*taxrate) into total;\nendif;\nselect total into ototal;\nend;\n# 关键词解释\n# create procedure 创建存储过程\n# in onumber int 表示是传入的参数 参数名 onumber int\n# comment 存储过程注释\n# begin 存储过程代码 开始\n# declare total decimal(8,2) 定义临时变量 total 变量类型 decimal(8,2)\n# into total 查询结果赋值给 total 变量\n# if taxable then 判断变量taxable 值是否为 true\n# endif 结束判断\n# end 存储过程结束\n\n# 存储过程解析\n# 定义了三个变量 一个传入的订单号 一个传入的是否查询税费 一个返回总计\n# 将根据参数订单号查询的订单商品价格总和赋值给 变量 total\n# 判断传入的参数taxable 是否为true 如果是将total + 定义的税费比例并重新赋值给total\n# 将total 赋值给返回的参数 ototal\n\ncall ordertotal(20005,0,@total);\n# 调用存储过程ordertotal 订单号 20005 不计算税费 返回参数@total\nselect @total;\n# 查询返回参数total\n\n```\n\n##### 检查存储过程\n\n```mysql\nshow create procedure ordertotal;\nshow procedure status like 'ordertotal';\nshow procedure status;\n```\n\n##### \n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkayw-geek%2Fmysql-note","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkayw-geek%2Fmysql-note","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkayw-geek%2Fmysql-note/lists"}