当前位置:网站首页>MySQL learning notes 2
MySQL learning notes 2
2022-07-06 01:14:00 【Bug No.1 quality inspector】
MySQL function
Common functions
-- Mathematical operations
SELECT ABS(-8) -- The absolute value
SELECT CEILING(9.4) -- Rounding up
SELECT FLOOR(9.4) -- Rounding down
SELECT RAND() -- return 0-1 random number
SELECT SIGN(-10) -- Judge the sign of a number 0-0 A negative number returns -1 A positive number returns 1
-- String function
SELECT CHAR_LENGTH('2323232') -- Return string length
SELECT CONCAT(' I ','233') -- String concatenation
SELECT INSERT('java',1,2,'cccc') -- Replace a length from a position
SELECT UPPER('abc')
SELECT LOWER('ABC')
SELECT REPLACE(' If you persist, you will succeed ',' insist ',' Strive ')
-- Check the last name Zhou Classmate , Change to Zou
SELECT REPLACE(studentname,' Zhou ',' Zou ') FROM student
WHERE studentname LIKE ' Zhou %'
-- Time and date functions ( remember )
SELECT CURRENT_DATE() -- Get current date
SELECT CURDATE() -- Get current date
SELECT NOW() -- Get current date
SELECT LOCATIME() -- Local time
SELECT SYSDATE() -- system time
SELECT YEAR(NOW())
SELECT MONTH(NOW())
SELECT DAY(NOW())
SELECT HOUR(NOW())
SELECT MINUTE(NOW())
SELECT SECOND(NOW())
-- System
SELECT SYSTEM_USER()
SELECT USER()
SELECT VERSION()
Aggregate functions ( Commonly used )
The name of the function | describe |
---|---|
COUNT() | Count |
SUM() | Sum up |
AVG() | Average |
MAX() | Maximum |
MIN() | minimum value |
… |
Database level MD5 encryption ( expand )
What is? MD5
It mainly enhances the complexity and irreversibility of the algorithm .
MD5 Irreversible , Concrete MD5 It's the same
MD5 Principle of cracking , There is a dictionary behind it ,MD5 Encrypted value , Value before encryption
CREATE TABLE `testmd5`(
`id` INT(4) NOT NULL,
`name` VARCHAR(20) NOT NULL,
`pwd` VARCHAR(50) NOT NULL,
PRIMARY KEY (`id`)
)ENGINE=INNODB DEFAULT CHARSET=UTF8
-- Plaintext password
INSERT INTO testmd5 VALUES(1,' Zhang San ','123456'),(2,' Li Si ','123456'),(3,' Wang Wu ','123456')
-- encryption
UPDATE testmd5 SET pwd=MD5(pwd) WHERE id =1
UPDATE testmd5 SET pwd=MD5(pwd) WHERE id !=1 -- Encrypt all
-- Encrypt on insert
INSERT INTO testmd5 VALUES(4,' Xiao Ming ',MD5('123456'))
INSERT INTO testmd5 VALUES(5,' red ',MD5('123456'))
-- How to check , The password passed by the user , Conduct MD5 encryption , Then compare the encrypted values
SELECT * FROM testmd5 WHERE `name`=' red ' AND pwd=MD5('123456')
Business
What is business
Business principles : ACID principle Atomicity , Uniformity , Isolation, , persistence ( Dirty reading , Fantasy reading …)
Atomicity (Atomicity)
Either they all succeed , Or they all failed
Uniformity (Consistency)
The data integrity before and after the transaction should be consistent
Isolation, (Isolation)
When multiple concurrent transactions occur , Mutual interference
persistence (Durability)– Transaction submission
Once a transaction is committed, it is irreversible , Be persisted to the database
Perform transactions :
-- mysql Automatically turn on transaction commit
SET autocommit=0 -- close
SET autocommit=1 -- Turn on ( default )
-- Handle transactions manually
SET autocommit =0 -- Turn off auto submit
-- The transaction open
START TRANSACTION -- Mark the beginning of a transaction , After this SQP All in the same transaction
INSERT XX
INSERT XX
-- Submit : Persistence ( success )
COMMIT
-- Roll back : Back to the original ( Failure )
ROLLBACK
-- End of transaction
SET autocommit = 1 -- Turn on auto submit
-- understand
SAVEPOINT Save point name -- Set a save point for a transaction
ROLLBACK TO SAVEPOINT Save roll call -- Roll back to savepoint
RELEASE SAVEPOINT Save it -- Delete savepoint
Simulate transfer transactions :
CREATE DATABASE shop CHARACTER SET utf8 COLLATE utf8_general_ci
USE shop
CREATE TABLE `account`(
`id` INT(3) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(30) NOT NULL,
`money` DECIMAL(9,2) NOT NULL,
PRIMARY KEY (`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO account(`name`,`money`)
VALUES('A',2000),('B',10000)
-- Analog transfer : Business
SET autocommit = 0; -- Turn off auto submit
START TRANSACTION -- Open transaction ( A set of transactions )
UPDATE account SET money = money-500 WHERE `name` = 'A' -- A Transfer to B
UPDATE account SET money = money+500 WHERE `name` = 'B' -- B Money received
COMMIT ; -- Commit transaction
ROLLBACK ; -- Roll back
SET autocommit=1 -- Restore defaults
Indexes
MySQL The establishment of index for MySQL It is very important to run efficiently , The index can be greatly improved MySQL Retrieval speed of .
Classification of indexes
In a table , The primary key index can only have one , There can be more than one unique index
primary key (PRIMARY KEY)
The only sign , The primary key cannot be repeated , There can only be one column as the primary key
unique index (UNIQUE KEY)
Avoid duplicate columns , The unique index can be repeated , Multiple columns can be identified as unique indexes
General index (KEY/INDEX)
default ,index,key Keyword to set
Full-text index (FULLTEXT)
Only under the characteristic database engine ,MyISAM
Quickly locate data
-- Use of index
-- 1. Add indexes to fields when creating tables
-- 2. After creation , Add index
-- Show all index information
SHOW INDEX FROM surface
-- Add an index
ALTER TABLE surface ADD FULLTEXT INDEX Index name ( Field name )
-- EXPLAIN analysis sql Implementation status
EXPLAIN SELECT * FROM student -- Non full text index
EXPLAIN SELECT * FROM student WHERE MATCH(studentName) AGAINST(' Liu ')
Test index
add to 100 Ten thousand data test indexes improve the query speed
CREATE TABLE `app_user` (
`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) DEFAULT '',
`email` VARCHAR(50) NOT NULL,
`phone` VARCHAR(20) DEFAULT '',
`gender` TINYINT(4) UNSIGNED DEFAULT '0',
`password` VARCHAR(100) NOT NULL DEFAULT '',
`age` TINYINT(4) DEFAULT NULL,
`create_time` DATETIME DEFAULT CURRENT_TIMESTAMP,
`update_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
-- Insert 100 All the data
DELIMITER $$ -- Before you write a function, you must write
CREATE FUNCTION mock_data()
RETURNS INT
BEGIN
DECLARE num INT DEFAULT 1000000;
DECLARE i INT DEFAULT 0;
WHILE i<num DO
-- Insert statement
INSERT INTO app_user(`name`,`email`,`phone`,`gender`,`password`,`age`)
VALUE(CONCAT(' user ',i),'[email protected]',FLOOR (CONCAT('18',RAND()*9999999)),FLOOR (RAND()*2),
UUID(),FLOOR (RAND()*100));
SET i = i+1;
END WHILE;
RETURN i;
END;
INSERT INTO app_user(`name`,`email`,`phone`,`gender`,`password`,`age`)
VALUE(CONCAT(' user ',i),'[email protected]',FLOOR (CONCAT('18',RAND()*9999999)),FLOOR (RAND()*2),
UUID(),FLOOR (RAND()*100))
SELECT mock_data();
SELECT * FROM app_user WHERE `name`=' user 9999' -- Nearly half a second
EXPLAIN SELECT * FROM app_user WHERE `name`=' user 9999' -- Inquire about 99999 Bar record
-- id _ Table name _ Field name
-- create index on Field
CREATE INDEX id_app_user_name ON app_user(`name`); -- 0.001 s
EXPLAIN SELECT * FROM app_user WHERE `name`=' user 9999' -- Look up a record
When indexing small data , Not very useful , But when it comes to big data , The difference is obvious
Indexing principles
- More indexes is not better
- Don't index frequently changing data
- A table with a small amount of data does not need to be indexed
- The index is usually added to the fields commonly used for query
The data structure of the index
Hash Index of type
Btree: Default innodb Data structure of
read : http://blog.codinglabs.org/articles/theory-of-mysql-index.html
Rights management and backup
User management
SQLyog Visual management
SQL The command operation
User table :mysql.user
The essence : Check this table , Additions and deletions
-- Create user CREATE USER user name IDENTIFIED BY ' password '
CREATE USER sanjin IDENTIFIED BY '123456'
-- Change Password ( Change the current password )
SET PASSWORD = PASSWORD('111111')
-- Change Password ( Change the specified user password )
SET PASSWORD FOR sanjin = PASSWORD('111111')
-- rename rename user Original name to New name
RENAME USER sanjin TO sanjin2
-- User authorization ALL PRIVILEGES All permissions library , surface
-- ALL PRIVILEGES In addition to empowering others , Everything else can
GRANT ALL PRIVILEGES ON *.* TO sanjin2
-- Query authority
SHOW GRANTS FOR sanjin2 -- View the permissions for the specified user
SHOW GRANTS FOR root@localhost
-- Revoke authority REVOKE What authority , In which library , To whom
REVOKE ALL PRIVILEGES ON *.* FROM sanjin2
-- Delete user
DROP USER sanjin2
MySQL Backup
Why backup :
- Ensure that important data is not lost
- Data transfer
MySQL The way of database backup
- Copy physical files directly
- stay SQLyog Manually export... In this visualization tool
- In the table or library you want to export , Right click to select backup and Export
Standardize database design
When the database is complex , We need to design
Bad database design :
- data redundancy , Waste space
- Database insertion and deletion are troublesome , abnormal 【 Shielding uses physical foreign keys 】
- The performance of the program is poor
Good database design :
- Save memory space
- Ensure the integrity of the database
- It's convenient for us to develop the system
Software development , About the design of database
- Analyze requirements : Analyze the business and the database needs to be processed
- Outline design : Design diagrams E-R chart
The steps to design a database ( Take personal blog as an example )
To collect information , Analyze requirements
- User table ( User login and logout , User's personal information , Blogging , Create classification )
- Classification table ( The article classification , Who created )
- Article table ( Information about the article )
- Friend list ( Friend chain information )
- Custom table ( system information , A key word , Or some main fields )
- Tell me about the watch ( Publish your mood …id ,content ,time)
Identifying entities ( Implement the requirements to each field )
Identify the relationship between entities
- Blogging user–>blog
- Create classification user–>category
- Focus on user–>user
- Friend chain –>links
- Comment on user–>user
Three paradigms
Why data normalization is needed ?
- Repetition of information
- Update exception
- Insertion exception
- Delete exception
The exception cannot be displayed normally
Loss of valid information
Three paradigms
First normal form (1NF)
- Atomicity : Make sure that each column is no longer divisible
Second normal form (2NF)
- Premise : Satisfy the first paradigm
- Each table only describes one thing
Third normal form (3NF)
- Premise : Satisfy the first paradigm and the second paradigm
- The third paradigm needs to ensure that each column of data in the data table is directly related to the primary key , Not indirectly .
Normative and performance issues
- Table associated with query , No more than three tables
- Consider the needs and goals of commercialization ( Cost and user experience ) Database performance is more important
- When re standardizing performance problems , It needs proper consideration , Normative
- Deliberately add some redundant fields to some tables ( From multiple tables , Turn it into a single table )
- Intentionally add some calculation Columns ( Reduce the amount of data from large to small : Indexes )
边栏推荐
- The basic usage of JMeter BeanShell. The following syntax can only be used in BeanShell
- MCU通过UART实现OTA在线升级流程
- FFT 学习笔记(自认为详细)
- Five challenges of ads-npu chip architecture design
- The value of applet containers
- 【第30天】给定一个整数 n ,求它的因数之和
- 关于#数据库#的问题:(5)查询库存表中每本书的条码、位置和借阅的读者编号
- Is chaozhaojin safe? Will it lose its principal
- MCU realizes OTA online upgrade process through UART
- WordPress collection plug-in automatically collects fake original free plug-ins
猜你喜欢
KDD 2022 | EEG AI helps diagnose epilepsy
Dedecms plug-in free SEO plug-in summary
Cf:d. insert a progression [about the insert in the array + the nature of absolute value + greedy top-down]
现货白银的一般操作方法
After Luke zettlemoyer, head of meta AI Seattle research | trillion parameters, will the large model continue to grow?
File upload vulnerability test based on DVWA
DOM introduction
The inconsistency between the versions of dynamic library and static library will lead to bugs
Opinions on softmax function
ORA-00030
随机推荐
MYSQL---查询成绩为前5名的学生
Netease smart enterprises enter the market against the trend, and there is a new possibility for game industrialization
vSphere实现虚拟机迁移
Vulhub vulnerability recurrence 75_ XStream
WordPress collection plug-in automatically collects fake original free plug-ins
KDD 2022 | EEG AI helps diagnose epilepsy
Who knows how to modify the data type accuracy of the columns in the database table of Damon
关于softmax函数的见解
DD's command
cf:H. Maximal AND【位运算练习 + k次操作 + 最大And】
Getting started with devkit
Leetcode sword finger offer 59 - ii Maximum value of queue
Synchronized and reentrantlock
Zhuhai laboratory ventilation system construction and installation instructions
SCM Chinese data distribution
Exciting, 2022 open atom global open source summit registration is hot
Recommended areas - ways to explore users' future interests
Blue Bridge Cup embedded stm32g431 - the real topic and code of the eighth provincial competition
About error 2003 (HY000): can't connect to MySQL server on 'localhost' (10061)
Kotlin core programming - algebraic data types and pattern matching (3)