MySQL (three) - a function, transaction, indexes, permissions management and backup, database design specifications

1. MySQL function

Official website: https: //dev.mysql.com/doc/refman/5.7/en/func-op-summary-ref.html

1.1 Common Functions

  • computation
SELECT ABS(-8) -- 绝对值 
SELECT CEILING(9.4) -- 向上取整 
SELECT FLOOR(9.4) -- 向下取整 
SELECT RAND() -- 返回一个 0~1 之间的随机数 
SELECT SIGN(10) -- 判断一个数的符号 0-0 负数返回-1,正数返回 1
  • String Functions
SELECT CHAR_LENGTH('即使再小的帆也能远航') -- 字符串长度 
SELECT CONCAT('我','爱','你们') -- 拼接字符串
SELECT INSERT('我爱编程helloworld',1,2,'超级热爱') -- 查询,从某个位置开始替换某个长度
SELECT LOWER('Dalao') -- 小写字母 
SELECT UPPER('Dalao') -- 大写字母 
SELECT INSTR('Dalao','a') -- 返回第一次出现的子串的索引 
SELECT REPLACE('大佬说坚持就能成功','坚持','努力') -- 替换出现的指定字符串 
SELECT SUBSTR('大佬说坚持就能成功',4,6) -- 返回指定的子字符串 (源字符串,截取的位置,截 取的长度) 
SELECT REVERSE('我是年少的欢喜') -- 反转 
  • Time and Date Functions (remember)
SELECT CURRENT_DATE() -- 获取当前日期 
SELECT CURDATE() -- 获取当前日期 
SELECT NOW() -- 获取当前的时间 
SELECT LOCALTIME() -- 本地时间 
SELECT SYSDATE() -- 系统时间 
SELECT YEAR(NOW()) 
SELECT MONTH(NOW()) 
SELECT DAY(NOW()) 
SELECT HOUR(NOW()) 
SELECT MINUTE(NOW()) 
SELECT SECOND(NOW())
  • System integration
SELECT SYSTEM_USER() 
SELECT USER() 
SELECT VERSION()

1.2 aggregate functions (commonly used)

Here Insert Picture Description

  • Data tables can be in the (To find out how many records there are a table, use the count ())
SELECT COUNT(`BornDate`) FROM student; -- Count(字段),会忽略所有的 null 值 
SELECT COUNT(*) FROM student; -- Count(*),不会忽略 null 值, 本质 计算行数 
SELECT COUNT(1) FROM result; -- Count(1),不会忽略忽略所有的 null 值 本质 计算 行数
SELECT SUM(`StudentResult`) AS 总和 FROM result 
SELECT AVG(`StudentResult`) AS 平均分 FROM result 
SELECT MAX(`StudentResult`) AS 最高分 FROM result 
SELECT MIN(`StudentResult`) AS 最低分 FROM result

1.3 MD5 encrypted database level

(1) What is MD5?
The main enhancement algorithm complexity and irreversibility.
MD5 irreversible, specific md5 value is the same
principle MD5 crack site, behind a dictionary, the value of the MD5 encryption, encryption of the previous value
(2) Test MD5 encryption

  • Plaintext password
    Here Insert Picture Description
  • Specifies the encryption password
    Here Insert Picture Description
  • Encrypt all passwords
    Here Insert Picture Description
  • Insertion of the encryption
    Here Insert Picture Description
  • How to verify : the user password passed in, for md5 encrypted, then the ratio of the value after the encrypted
    Here Insert Picture Description

2. Transaction

2.1 Description

MySQL transaction is mainly used for data manipulation volume, high complexity of the process . For example, in personnel management system, you delete a person, you only need to remove the basic information of personnel, and also to delete the personnel-related information, such as mail, articles, etc., so that the database operation statement constitutes a transaction !

2.2 Principles Affairs

Generally speaking, the transaction must meet four conditions ( the ACID ): atomicity (Atomicity, also known as indivisibility), consistency (Consistency), isolation (Isolation, also known as independence), persistent (Durability)

  • Atomicity (Atomicity)
    either succeed or fail
  • Consistency (Consistency)
    data before and after the transaction integrity to ensure consistency
  • Isolation (Isolation)
    transaction isolation when a plurality of users concurrent access to the database, the user opens a database for each transaction, the operation data can not be disturbed by other transactions, for isolation between a plurality of concurrent transactions.
  • Persistent (Durability Rev)
    Once the transaction submitted by the irreversible, is persisted to the database

Some of the problems caused by isolation 2.3

  • Dirty read
    refers to a transaction reads data of another uncommitted transactions.
  • Non-repeatable read
    to read a row of the table in a data transaction, read many times different results. (This is not necessarily wrong, but some cases do not)
  • Dummy read (read phantom)
    means within a read transaction to insert other transaction data, resulting in inconsistent reading.

2.4 Executive Affairs

-- mysql 是默认开启事务自动提交的 
SET autocommit = 0  -- 关闭 
SET autocommit = 1  -- 开启(默认的)

-- 手动处理事务 
SET autocommit = 0 -- 关闭自动提交 

-- 事务开启 
START TRANSACTION -- 标记一个事务的开始,从这个之后的 sql 都在同一个事务内 
INSERT xx 
INSERT xx 

-- 提交: 持久化 (成功!) 
COMMIT 
-- 回滚: 回到的原来的样子 (失败!) 
ROLLBACK 

-- 事务结束 
SET autocommit = 1 -- 开启自动提交 

-- 了解 
SAVEPOINT 保存点名 -- 设置一个事务的保存点 
ROLLBACK TO SAVEPOINT 保存点名 -- 回滚到保存点 
RELEASE SAVEPOINT 保存点名 -- 撤销保存点 

2.5 simulation scenarios

  • A 2000 SQL execution transfer A to B 500
  • B 10000 SQL execution B 500 A is received
    Here Insert Picture Description

3. Index

MySQL is the official definition of the index: the index (Index) to help MySQL efficiently get the data structure of the data.
Extracting a sentence trunk, you can get the essence of the index: the index is a data structure .

3.1 Classification Index

In a table, the primary key index can have a unique index may have a plurality of
(1) primary key index (PRIMARY KEY)
a unique identifier, the primary key is unique to only one column as the primary key
(2) a unique index (UNIQUE KEY )
to avoid duplicate column appeared, a unique index can be repeated, multiple columns can flag a unique index
(3) General index (KEY / iNDEX)
default, index, key keyword set
(4) full-text index (FullText)
in only, MyISAM database engine under certain
fast positioning data

  • Basic grammar
-- 索引的使用 
-- 1、在创建表的时候给字段增加索引 
-- 2、创建完毕后,增加索引 
-- 显示所有的索引信息 
SHOW INDEX FROM student 
-- 增加一个全文索引 (索引名) 列名 
ALTER TABLE school.student ADD FULLTEXT INDEX `studentName`(`studentName`); 
-- EXPLAIN 分析sql执行的状况 
EXPLAIN SELECT * FROM student; -- 非全文索引 
EXPLAIN SELECT * FROM student WHERE MATCH(studentName) AGAINST('刘'); 

3.2 Testing Index

CREATE TABLE `app_user` ( 
`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, 
`name` VARCHAR(50) DEFAULT '' COMMENT '用户昵称', 
`email` VARCHAR(50) NOT NULL COMMENT '用户邮箱', 
`phone` VARCHAR(20) DEFAULT '' COMMENT '手机号', 
`gender` TINYINT(4) UNSIGNED DEFAULT '0' COMMENT '性别(0:男;1:女)', 
`password` VARCHAR(100) NOT NULL COMMENT '密码', 
`age` TINYINT(4) DEFAULT '0' COMMENT '年龄', 
`create_time` DATETIME DEFAULT CURRENT_TIMESTAMP, 
`update_time` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE 
CURRENT_TIMESTAMP, 
PRIMARY KEY (`id`) 
) ENGINE=INNODB DEFAULT CHARSET=utf8mb4 COMMENT='app用户表'

-- 插入100万数据 
DELIMITER $$ -- 写函数之前必须要写,标志 
CREATE FUNCTION mock_data() 
RETURNS INT 
BEGIN
DECLARE num INT DEFAULT 1000000; 
DECLARE i INT DEFAULT 0; 
WHILE i<num DO 
INSERT INTO 
app_user(`name`,`email`,`phone`,`gender`,`password`,`age`)VALUES(CONCAT('用 户',i),'[email protected]',CONCAT('18',FLOOR(RAND()*((999999999- 100000000)+100000000))),FLOOR(RAND()*2),UUID(),FLOOR(RAND()*100)); 
SET i = i+1;
END WHILE; 
RETURN i; 
END; 
SELECT mock_data();
SELECT * FROM app_user WHERE `name` = '用户9999'; --  0.344 sec 
EXPLAIN SELECT * FROM app_user WHERE `name` = '用户9999';

-- id _ 表名 _ 字段名 
-- CREATE INDEX 索引名 on 表(字段)
CREATE INDEX id_app_user_name ON app_user(`name`);
SELECT * FROM app_user WHERE `name` = '用户9999';  -- 0 sec
EXPLAIN SELECT * FROM app_user WHERE `name` = '用户9999';
  • Index data in a small amount of time, not very useful, but in dealing with large data when the difference is very obvious

3.3 Principles Index

  • The index is not better
  • Do not change the data indexed to the process
  • A small amount of data does not require indexing table
  • Index generally applied to the fields used to query!

Reference reading: http: //blog.codinglabs.org/articles/theory-of-mysql-index.html

4. permissions management and backup

4.1 User Management

  • SQL yog visual management
    Here Insert Picture Description
  • SQL command operations
    user tables: mysql.user
    nature: Read this table CRUD
-- 创建用户 CREATE USER 用户名 IDENTIFIED BY '密码' 
CREATE USER dalao IDENTIFIED BY '123456' 

-- 修改密码 (修改当前用户密码) 
SET PASSWORD = PASSWORD('123456') 

-- 修改密码 (修改指定用户密码) 
SET PASSWORD FOR dalao = PASSWORD('123456') 

-- 重命名 RENAME USER 原来名字 TO 新的名字 
RENAME USER dalao TO dalao2 

-- 用户授权 ALL PRIVILEGES 全部的权限 , 库.表 
-- ALL PRIVILEGES 除了给别人授权,其他都能够干 
GRANT ALL PRIVILEGES ON *.* TO dalao2 

-- 查询权限 
SHOW GRANTS FOR dalao2 -- 查看指定用户的权限 
SHOW GRANTS FOR root@localhost 

-- ROOT用户权限:GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION 
-- 撤销权限 REVOKE 哪些权限, 在哪个库撤销,给谁撤销 
REVOKE ALL PRIVILEGES ON *.* FROM dalao2 

-- 删除用户 
DROP USER dalao

Exercise: Create a user CREATE USER username IDENTIFIED BY 'password'
Here Insert Picture Description

4.2 MySQL Backup

The reason (1) backup

  • To ensure that important data is not lost
  • Data transfer

Fashion (2) MySQL database backup

  • Direct physical file copy
  • In this manual export Sqlyog visualizer
    Here Insert Picture Description
  • Mysqldump to export using the command line using the command line
# mysqldump -h 主机 -u 用户名 -p 密码 数据库 表名 > 物理磁盘位置/文件名 
mysqldump -hlocalhost -uroot -p123456 school student >D:/a.sql 

# mysqldump -h 主机 -u 用户名 -p 密码 数据库 表1 表2 表3 > 物理磁盘位置/文件名
mysqldump -hlocalhost -uroot -p123456 school student >D:/b.sql 

# mysqldump -h 主机 -u 用户名 -p 密码 数据库> 物理磁盘位置/文件名 
mysqldump -hlocalhost -uroot -p123456 school >D:/c.sql 

# 导入 
# 登录的情况下,切换到指定的数据库 
# source 备份文件 
source d:/a.sql 
mysql -u用户名 -p密码 库名< 备份文件

The design specification database

5.1 Design of reasons

When the database is more complex, we need to design
(1) poor database design

  • Data redundancy, waste of space
  • Insert and delete databases are cumbersome, abnormal physical shielding foreign keys []
  • Poor performance of the program

(2) good database design

  • Save memory space
  • Ensure the integrity of the database
  • We facilitate the development system

(3) software development, database design on

  • Demand analysis: analysis of business needs and databases need to be addressed
  • Summary of design: design diagram ER diagram

(4) step in the design of the database (personal blog)

  • Gather information, analyze the needs of
    the user table (user login logout, the user's personal information, write a blog, create a classification)
    classification (article categories, who created)
    article table (information of the article)
    Comments table
    Friends list (Friends of the chain of information)
    from Definition table (system information, a key word, or some primary field) key: value
    talk about the table (published mood ... id ... content ... .create_time)
  • Identify the entity (the floor needs to each field)
  • The relationship between the identification entity
    to blog: user -> blog
    creation Category: user -> category
    concern: user -> user
    friendly chain: links
    Comments: user-user-blog

Three Forms 5.2

(1) Why do you need data normalization?

  • Duplication of information
  • Update anomalies
  • Insert an exception
    can not properly display information
  • Delete abnormal
    loss of valid information

(2) the three major paradigms

  • The first paradigm (1NF)
    atomicity: to ensure that each column can not be divided
  • Second Normal Form (2NF)
    premise: to meet the first paradigm
    each table describe only one thing
  • The third paradigm (3NF)
    provided: first normal and the second normal satisfies
    a third paradigm need to ensure that each column of data in the table are directly related to the primary key, and not indirectly.

(3) regulatory issues and performance
table associated with the query may not exceed three tables

  • Consider the commercial needs and objectives (cost, user experience!) Database performance is more important
  • When the performance of regulatory issues, it is necessary to consider the appropriate normative!
  • Deliberately add some redundancy to some table fields. (From multi-table queries into a single-table queries)
  • Deliberately increase the number of computed column (reduced from large amounts of data into small data query: index)
Published 62 original articles · won praise 2 · Views 2737

Guess you like

Origin blog.csdn.net/nzzynl95_/article/details/104090237