当前位置:网站首页>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 )
边栏推荐
- Overview of Zhuhai purification laboratory construction details
- Is chaozhaojin safe? Will it lose its principal
- WGet: command line download tool
- Paging of a scratch (page turning processing)
- 282. Stone consolidation (interval DP)
- False breakthroughs in the trend of London Silver
- JMeter BeanShell的基本用法 一下语法只能在beanshell中使用
- A preliminary study of geojson
- Leetcode study - day 35
- Gartner发布2022-2023年八大网络安全趋势预测,零信任是起点,法规覆盖更广
猜你喜欢
ADS-NPU芯片架构设计的五大挑战
ORA-00030
Kotlin basics 1
Daily practice - February 13, 2022
About error 2003 (HY000): can't connect to MySQL server on 'localhost' (10061)
Dedecms plug-in free SEO plug-in summary
基於DVWA的文件上傳漏洞測試
Starting from 1.5, build a micro Service Framework - call chain tracking traceid
毕设-基于SSM高校学生社团管理系统
DOM introduction
随机推荐
MobileNet系列(5):使用pytorch搭建MobileNetV3并基于迁移学习训练
golang mqtt/stomp/nats/amqp
Modify the ssh server access port number
Three methods of script about login and cookies
Recommended areas - ways to explore users' future interests
The basic usage of JMeter BeanShell. The following syntax can only be used in BeanShell
Kotlin basics 1
Leetcode 剑指 Offer 59 - II. 队列的最大值
ORA-00030
测试/开发程序员的成长路线,全局思考问题的问题......
The growth path of test / development programmers, the problem of thinking about the overall situation
How to see the K-line chart of gold price trend?
Distributed base theory
在产业互联网时代,将会凭借大的产业范畴,实现足够多的发展
Leetcode study - day 35
Cve-2017-11882 reappearance
Live broadcast system code, custom soft keyboard style: three kinds of switching: letters, numbers and punctuation
Zhuhai's waste gas treatment scheme was exposed
现货白银的一般操作方法
伦敦银走势中的假突破