当前位置:网站首页>Introduction to MySQL basics day3 power node [Lao Du] class notes
Introduction to MySQL basics day3 power node [Lao Du] class notes
2022-06-30 08:35:00 【hty2dby】
day_3
The original author of this article is Mr. Du, the teaching director of power node. Mr. Du is in his class Lao Du will take you to learn _mysql Fundamentals of entry (mysql Basic video + Database practice ) Lecture notes written
See the link at the end of the document for this document and related materials
I will take notes of the lecture txt After downloading , To convert into markdown Format , And some of the contents are added , Original investment area , In case of infringement , Must delete
The text description at the bottom of the original video is as follows :
This set is MySQL The database video tutorial is told by Mr. Du, the teaching director of power node , Which explains in detail MySQL Knowledge about , Include MySQL summary ,MySQL Application environment ,MySQL System features ,MySQL Beginners ,MySQL Management tools , How to install MySQL And MySQL New characteristics , By watching this set Java Video tutorial can master MySQL Full knowledge
1. Query the Department name of each employee ? Employee name and department name are required
mysql> select * from emp;
+-------+--------+-----------+------+------------+---------+---------+--------+
| EMPNO | ENAME | JOB | MGR | HIREDATE | SAL | COMM | DEPTNO |
+-------+--------+-----------+------+------------+---------+---------+--------+
| 7369 | SMITH | CLERK | 7902 | 1980-12-17 | 800.00 | NULL | 20 |
| 7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 | 1600.00 | 300.00 | 30 |
| 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250.00 | 500.00 | 30 |
| 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975.00 | NULL | 20 |
| 7654 | MARTIN | SALESMAN | 7698 | 1981-09-28 | 1250.00 | 1400.00 | 30 |
| 7698 | BLAKE | MANAGER | 7839 | 1981-05-01 | 2850.00 | NULL | 30 |
| 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450.00 | NULL | 10 |
| 7788 | SCOTT | ANALYST | 7566 | 1987-04-19 | 3000.00 | NULL | 20 |
| 7839 | KING | PRESIDENT | NULL | 1981-11-17 | 5000.00 | NULL | 10 |
| 7844 | TURNER | SALESMAN | 7698 | 1981-09-08 | 1500.00 | 0.00 | 30 |
| 7876 | ADAMS | CLERK | 7788 | 1987-05-23 | 1100.00 | NULL | 20 |
| 7900 | JAMES | CLERK | 7698 | 1981-12-03 | 950.00 | NULL | 30 |
| 7902 | FORD | ANALYST | 7566 | 1981-12-03 | 3000.00 | NULL | 20 |
| 7934 | MILLER | CLERK | 7782 | 1982-01-23 | 1300.00 | NULL | 10 |
+-------+--------+-----------+------+------------+---------+---------+--------+
mysql> select * from dept;
+--------+------------+----------+
| DEPTNO | DNAME | LOC |
+--------+------------+----------+
| 10 | ACCOUNTING | NEW YORK |
| 20 | RESEARCH | DALLAS |
| 30 | SALES | CHICAGO |
| 40 | OPERATIONS | BOSTON |
+--------+------------+----------+
from emp From the table ename, from dept From the table dname, There are no conditions. The final query result is ?
ENAME DNAME
-------------------------------------------
SMITH ACCOUNTING Invalid record
SMITH RESEARCH Effective records
SMITH SALES Invalid record
SMITH OPERATIONS Invalid record
ALLEN ACCOUNTING
ALLEN RESEARCH
ALLEN SALES
ALLEN OPERATIONS
.....
56 Bar record . Add a condition to achieve 4 choose 1, Also for the validity of data .
select
e.ename,d.dname
from
emp e
join
dept d
on
e.deptno = d.deptno;
Conditions are only added to avoid Cartesian product phenomenon , Just to find out the valid combination records .
The number of matches is not less , still 56 Time .
2. insert Statement can insert more than one record at a time ?【 master 】
Tolerable !
mysql> desc t_user;
+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| name | varchar(32) | YES | | NULL | |
| birth | date | YES | | NULL | |
| create_time | datetime | YES | | NULL | |
+-------------+-------------+------+-----+---------+-------+
Multiple records can be inserted at a time :
insert into t_user(id,name,birth,create_time) values
(1,'zs','1980-10-11',now()),
(2,'lisi','1981-10-11',now()),
(3,'wangwu','1982-10-11',now());
grammar :insert into t_user( Field name 1, Field name 2) values(),(),(),();
mysql> select * from t_user;
+------+--------+------------+---------------------+
| id | name | birth | create_time |
+------+--------+------------+---------------------+
| 1 | zs | 1980-10-11 | 2020-03-19 09:37:01 |
| 2 | lisi | 1981-10-11 | 2020-03-19 09:37:01 |
| 3 | wangwu | 1982-10-11 | 2020-03-19 09:37:01 |
+------+--------+------------+---------------------+
3. Create tables quickly ?【 Understand the content 】
mysql> create table emp2 as select * from emp;
principle :
- Create a new query result as a table !!!!!
- This can complete the fast copy of the table !!!!
- Create a table , At the same time, the data in the table also exists !!!
create table mytable as select empno,ename from emp where job = 'MANAGER';
4. Insert the query results into a table ?insert dependent !!!【 Understand the content 】
create table dept_bak as select * from dept;
mysql> select * from dept_bak;
+--------+------------+----------+
| DEPTNO | DNAME | LOC |
+--------+------------+----------+
| 10 | ACCOUNTING | NEW YORK |
| 20 | RESEARCH | DALLAS |
| 30 | SALES | CHICAGO |
| 40 | OPERATIONS | BOSTON |
+--------+------------+----------+
insert into dept_bak select * from dept; // Rarely used !
mysql> select * from dept_bak;
+--------+------------+----------+
| DEPTNO | DNAME | LOC |
+--------+------------+----------+
| 10 | ACCOUNTING | NEW YORK |
| 20 | RESEARCH | DALLAS |
| 30 | SALES | CHICAGO |
| 40 | OPERATIONS | BOSTON |
| 10 | ACCOUNTING | NEW YORK |
| 20 | RESEARCH | DALLAS |
| 30 | SALES | CHICAGO |
| 40 | OPERATIONS | BOSTON |
+--------+------------+----------+
5. Quickly delete data from a table ?【truncate More important , Must master 】
// Delete dept_bak Table data
delete from dept_bak; // This method of deleting data is slow .
mysql> select * from dept_bak;
Empty set (0.00 sec)
delete Statement to delete data ?(delete Belong to DML sentence !!!)
The data in the table has been deleted , However, the real storage space of this data on the hard disk will not be released !!!
The disadvantage of this deletion is : Deletion efficiency is relatively low . The advantage of this deletion is : Support rollback , If you regret it, you can restore the data !!!
truncate Statement to delete data ?
This deletion is more efficient , The table was truncated once , Physical delete .
This deletion has the disadvantage of : Rollback is not supported . This deletion has the advantage of : Fast .
usage :truncate table dept_bak; ( This operation belongs to DDL operation .)
The big watch is very big , Hundreds of millions of records ????
When deleting , Use delete, You may need to perform 1 It takes hours to delete ! Low efficiency . You can choose to use truncate Delete data from table . Need less than 1 The deletion ends in seconds . More efficient . But use truncate Before , The customer must be asked carefully whether they really want to delete it , And warn that it cannot be recovered after deletion !
truncate Is to delete the data in the table , The watch is still there !
Delete table operation ?
drop table Table name ; // This is not to delete the data in the table , This is to delete the table .
6. The addition, deletion and modification of the table structure ?
What is the modification of table structure ?
Add a field , Delete a field , Modify a field !!!
To modify the table structure, you need to use :alter, Belong to DDL sentence
DDL Include :
create drop alter
- In actual development , Once the requirements are determined , Once the watch is designed , Few changes to the table structure . Because when development is in progress , Modify table structure , The cost is relatively high . Modify the structure of the table , Corresponding java The code needs a lot of modification . The cost is relatively high . This responsibility should be borne by the designer !
- Because there are few operations to modify the table structure , So we don't need to master , If you want to modify the table structure one day , You can use tools !!!!
The operation of modifying the table structure does not need to be written to java In program . Not really java The category of programmers .
7. constraint ( It's very important , Five stars *****)
7.1. What are constraints ?
Constrain the corresponding English word :constraint
When creating tables , We can add some constraints to the fields in the table , To ensure the integrity of the data in this table 、 effectiveness !!!
The function of constraints is to ensure : The data in the table is valid !!
7.2. What are the constraints ?
- Non empty constraint :not null
- Uniqueness constraint : unique
- Primary key constraint : primary key ( abbreviation PK)
- Foreign key constraints :foreign key( abbreviation FK)
- Check constraint :check(mysql I won't support it ,oracle Support )
Here we focus on four constraints :
not null
unique
primary key
foreign key
7.3. Non empty constraint :not null
Non empty constraint not null Constraint field cannot be NULL
drop table if exists t_vip;
create table t_vip(
id int,
name varchar(255) not null // not null Only column level constraints , No table level constraints !
);
insert into t_vip(id,name) values(1,'zhangsan');
insert into t_vip(id,name) values(2,'lisi');
insert into t_vip(id) values(3);
ERROR 1364 (HY000): Field 'name' doesn't have a default value
7.3.1. episode
xxxx.sql Such documents are called sql Script files .sql A large number of... Are written in the script file sql sentence .
We execute sql Script files , All... In this file sql The statement will all execute !
Batch execution SQL sentence , have access to sql Script files . stay mysql How to execute sql The script ?
mysql> source D:\course\03-MySQL\document\vip.sql
In your actual work , The first day I arrived at the company , The project manager will give you a xxx.sql file , You execute this script file , You have the database data on your computer !
7.4. Uniqueness constraint : unique
Uniqueness constraint unique Constraint fields cannot be repeated , But it can be for NULL.
drop table if exists t_vip;
create table t_vip(
id int,
name varchar(255) unique,
email varchar(255)
);
insert into t_vip(id,name,email) values(1,'zhangsan','[email protected]');
insert into t_vip(id,name,email) values(2,'lisi','[email protected]');
insert into t_vip(id,name,email) values(3,'wangwu','[email protected]');
select * from t_vip;
insert into t_vip(id,name,email) values(4,'wangwu','[email protected]');
ERROR 1062 (23000): Duplicate entry 'wangwu' for key 'name'
insert into t_vip(id) values(4);
insert into t_vip(id) values(5);
+------+----------+------------------+
| id | name | email |
+------+----------+------------------+
| 1 | zhangsan | zhangsan@123.com |
| 2 | lisi | lisi@123.com |
| 3 | wangwu | wangwu@123.com |
| 4 | NULL | NULL |
| 5 | NULL | NULL |
+------+----------+------------------+
name Although the field is unique Constrained , But it can be for NULL.
The new demand :name and email The two fields are unique when combined !!!!
drop table if exists t_vip;
create table t_vip(
id int,
name varchar(255) unique, // The constraint is added directly to the column , It's called column level constraints .
email varchar(255) unique
);
The creation of this table is not in line with my above “ The new demand ” Of .
This creates a representation :name Have uniqueness ,email Have uniqueness . Each is unique .
The following data is consistent with “ The new demand ” Of .
insert into t_vip(id,name,email) values(1,'zhangsan','[email protected]');
insert into t_vip(id,name,email) values(2,'zhangsan','[email protected]');
But if you create a table in the above way , Definitely failed to create , because ’zhangsan’ and ’zhangsan’ repeated .
How to create such a table , To meet new needs ?
drop table if exists t_vip;
create table t_vip(
id int,
name varchar(255),
email varchar(255),
unique(name,email) // The constraint is not added after the column , This constraint is called a table level constraint .
);
insert into t_vip(id,name,email) values(1,'zhangsan','[email protected]');
insert into t_vip(id,name,email) values(2,'zhangsan','[email protected]');
select * from t_vip;
name and email The two fields combine to be unique !!!
insert into t_vip(id,name,email) values(3,'zhangsan','[email protected]');
ERROR 1062 (23000): Duplicate entry '[email protected]' for key 'name'
When to use table level constraints ?
When you need to combine multiple fields to add a constraint , Need to use table level constraints .
unique and not null Can we unite ?
drop table if exists t_vip;
create table t_vip(
id int,
name varchar(255) not null unique
);
mysql> desc t_vip;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| name | varchar(255) | NO | PRI | NULL | |
+-------+--------------+------+-----+---------+-------+
stay mysql among , If a field is simultaneously not null and unique Bound words ,
This field automatically becomes the primary key field .( Be careful :oracle It's different !)
insert into t_vip(id,name) values(1,'zhangsan');
insert into t_vip(id,name) values(2,'zhangsan'); // Wrong. :name Can't repeat
insert into t_vip(id) values(2); // Wrong. :name Not for NULL.
7.5. Primary key constraint (primary key, abbreviation PK) Very important five stars *****
7.5.1. Terms related to primary key constraints ?
- Primary key constraint : It's a constraint .
- Primary key field : A primary key constraint is added to this field , Such fields are called : Primary key field
- Primary key value : Each value in the primary key field is called : Primary key value .
7.5.2. What is a primary key ? What's the use ?
The primary key value is the unique identification of each row of records . The primary key value is the ID number of each row. !!!
remember : Any table should have a primary key , There is no primary key , Invalid table !!
The characteristics of primary keys :not null + unique( The primary key value cannot be NULL, At the same time, you can't repeat !)
7.5.3. How to add a primary key constraint to a table ?
// Column level constraints
drop table if exists t_vip;
// 1 A field is used as the primary key , be called : Single primary key
create table t_vip(
id int primary key,
name varchar(255)
);
insert into t_vip(id,name) values(1,'zhangsan');
insert into t_vip(id,name) values(2,'lisi');
// error : Can't repeat
insert into t_vip(id,name) values(2,'wangwu');
ERROR 1062 (23000): Duplicate entry '2' for key 'PRIMARY'
// error : Not for NULL
insert into t_vip(name) values('zhaoliu');
ERROR 1364 (HY000): Field 'id' doesn't have a default value
7.5.4. Can I add a primary key like this , Use table level constraints ?
Tolerable
// Table level constraints
drop table if exists t_vip;
create table t_vip(
id int,
name varchar(255),
primary key(id)
);
insert into t_vip(id,name) values(1,'zhangsan');
// error
insert into t_vip(id,name) values(1,'lisi');
ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'
7.5.5. Table level constraints are mainly used to add constraints to multiple fields ?
drop table if exists t_vip;
// id and name Join forces to do : Composite primary key !!!!
create table t_vip(
id int,
name varchar(255),
email varchar(255),
primary key(id,name)
);
insert into t_vip(id,name,email) values(1,'zhangsan','[email protected]');
insert into t_vip(id,name,email) values(1,'lisi','[email protected]');
// error : Can't repeat
insert into t_vip(id,name,email) values(1,'lisi','[email protected]');
ERROR 1062 (23000): Duplicate entry '1-lisi' for key 'PRIMARY'
In actual development, it is not recommended to use : Composite primary key . A single primary key is recommended !
Because the significance of the primary key value is the ID number of this row. , As long as the meaning is achieved , A single primary key can do . Composite primary keys are complex , Not recommended !!!
7.5.6. Can I add two primary key constraints to a table ?
drop table if exists t_vip;
create table t_vip(
id int primary key,
name varchar(255) primary key
);
ERROR 1068 (42000): Multiple primary key defined
Conclusion : A watch , Primary key constraints can only be added 1 individual .( The primary key can only have 1 individual .)
The primary key value is recommended to use :int, bigint, char Other types .
Not recommended :varchar To make the primary key . Primary key values are usually numbers , It's usually fixed length !
7.5.7. Except : Except single primary key and composite primary key , It can also be classified in this way ?
Naturally : The primary key value is a natural number , It has nothing to do with business .
Business primary key : The primary key value is closely related to the business , For example, take the bank card account number as the main key value . This is the business primary key !
7.5.8. There are many ways to use business primary keys in actual development , Or use more natural primary keys ?
Natural primary keys are used more , Because as long as the primary key is not repeated , It doesn't need to be meaningful .
Bad business primary key , Because once the primary key is linked to the business , So when the business changes , It may affect the primary key value , Therefore, business PK is not recommended . Try to use natural primary keys .
7.5.9. Automatically maintain a primary key value
//auto_increment Said the increase , from 1 Start , With 1 Increasing !
drop table if exists t_vip;
create table t_vip(
id int primary key auto_increment,
name varchar(255)
);
insert into t_vip(name) values('zhangsan');
insert into t_vip(name) values('zhangsan');
insert into t_vip(name) values('zhangsan');
insert into t_vip(name) values('zhangsan');
insert into t_vip(name) values('zhangsan');
insert into t_vip(name) values('zhangsan');
insert into t_vip(name) values('zhangsan');
insert into t_vip(name) values('zhangsan');
select * from t_vip;
+----+----------+
| id | name |
+----+----------+
| 1 | zhangsan |
| 2 | zhangsan |
| 3 | zhangsan |
| 4 | zhangsan |
| 5 | zhangsan |
| 6 | zhangsan |
| 7 | zhangsan |
| 8 | zhangsan |
+----+----------+
7.6. Foreign key constraints (foreign key, abbreviation FK) Very important five stars *****
7.6.1. Terms related to foreign key constraints
- Foreign key constraints : A constraint (foreign key)
- Foreign key field : A foreign key constraint is added to this field
- Foreign key value : Every value in the foreign key field .
7.6.2. Business background
Please design the database table , To describe “ Class and students ” Information about ?
First option : Classes and students are stored in a table ???
t_student
no(pk) name classno classname
----------------------------------------------------------------------
1 jack 100 Senior 3, No. 2 middle school, Yizhuang Town, Daxing District, Beijing 1 class
2 lucy 100 Senior 3, No. 2 middle school, Yizhuang Town, Daxing District, Beijing 1 class
3 lilei 100 Senior 3, No. 2 middle school, Yizhuang Town, Daxing District, Beijing 1 class
4 hanmeimei 100 Senior 3, No. 2 middle school, Yizhuang Town, Daxing District, Beijing 1 class
5 zhangsan 101 Senior 3, No. 2 middle school, Yizhuang Town, Daxing District, Beijing 2 class
6 lisi 101 Senior 3, No. 2 middle school, Yizhuang Town, Daxing District, Beijing 2 class
7 wangwu 101 Senior 3, No. 2 middle school, Yizhuang Town, Daxing District, Beijing 2 class
8 zhaoliu 101 Senior 3, No. 2 middle school, Yizhuang Town, Daxing District, Beijing 2 class
Analyze the disadvantages of the above scheme :
data redundancy , Space waste !!!! This design is a failure !
Second option : Class a table 、 Students a table ??
t_class Class table
classno(pk) classname
------------------------------------------------------
100 Senior 3, No. 2 middle school, Yizhuang Town, Daxing District, Beijing 1 class
101 Senior 3, No. 2 middle school, Yizhuang Town, Daxing District, Beijing 1 class
t_student Student list
no(pk) name cno(FK quote t_class This watch is classno)
-------------------------------------------------------------
1 jack 100
2 lucy 100
3 lilei 100
4 hanmeimei 100
5 zhangsan 101
6 lisi 101
7 wangwu 101
8 zhaoliu 101
When cno When the field has no constraints , May cause invalid data . There could be a 102, however 102 Class does not exist .
So to make sure cno The values in the field are 100 and 101, Need to give cno Field add foreign key constraint , that cno Fields are foreign key fields ,cno Each value in the field is a foreign key value .
7.6.3. Be careful
t_class It's the father's watch ,t_student It's a subtable
The order in which tables are deleted ? Delete the sub first , Then delete the father .
The order in which tables are created ? Create the parent first , Create Jianzi again .
The order in which data is deleted ? Delete the sub first , Then delete the father .
The order in which the data is inserted ? Insert parent first , Then insert the sub .
reflection : The foreign key in the child table refers to a field in the parent table , Must the referenced field be a primary key ?
Not necessarily the primary key , But at least it has unique constraint .
7.6.4. Foreign key can be NULL Do you ?
The foreign key value can be NULL.
7.6.5. Create foreign key constraints
// foreign key( Foreign key name ) references Table name ( Field name )
create table students(
id int auto_increment primary key,
uid int not null,
name varchar(6) not null,
foreign key(uid) references class(xuehao)
);
8. Storage engine ( Understand the content )
8.1. What is a storage engine , What's the use ?
The storage engine is MySQL A term peculiar to , Not in other databases .(Oracle There is , But not by that name )
The name of storage engine is high-end and high-grade , In fact, the storage engine is a table storage / How to organize data . Different storage engines , Tables store data differently .
8.2. How to add... To a table / Appoint “ Storage engine ” Well ?
show create table t_student;
You can assign a storage engine to the table when creating the table .
CREATE TABLE `t_student` (
`no` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`cno` int(11) DEFAULT NULL,
PRIMARY KEY (`no`),
KEY `cno` (`cno`),
CONSTRAINT `t_student_ibfk_1` FOREIGN KEY (`cno`) REFERENCES `t_class` (`classno`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8
When creating a table, it can be in the last parenthesis ")" Use... On the right of :
- ENGINE To specify the storage engine .
- CHARSET To specify the character encoding of this table .
8.2.1. Conclusion
mysql The default storage engine is :InnoDB, The default character encoding method is :utf8
Specify the storage engine when creating the table , And character encoding .
create table t_product(
id int primary key,
name varchar(255)
)engine=InnoDB default charset=gbk;
8.3. How to check mysql What storage engines are supported ?
mysql> select version();
+-----------+
| version() |
+-----------+
| 5.5.36 |
+-----------+
command :
show engines \G
*************************** 1. row ***************************
Engine: FEDERATED
Support: NO
Comment: Federated MySQL storage engine
Transactions: NULL
XA: NULL
Savepoints: NULL
*************************** 2. row ***************************
Engine: MRG_MYISAM
Support: YES
Comment: Collection of identical MyISAM tables
Transactions: NO
XA: NO
Savepoints: NO
*************************** 3. row ***************************
Engine: MyISAM
Support: YES
Comment: MyISAM storage engine
Transactions: NO
XA: NO
Savepoints: NO
*************************** 4. row ***************************
Engine: BLACKHOLE
Support: YES
Comment: /dev/null storage engine (anything you write to it disappears
Transactions: NO
XA: NO
Savepoints: NO
*************************** 5. row ***************************
Engine: CSV
Support: YES
Comment: CSV storage engine
Transactions: NO
XA: NO
Savepoints: NO
*************************** 6. row ***************************
Engine: MEMORY
Support: YES
Comment: Hash based, stored in memory, useful for temporary tables
Transactions: NO
XA: NO
Savepoints: NO
*************************** 7. row ***************************
Engine: ARCHIVE
Support: YES
Comment: Archive storage engine
Transactions: NO
XA: NO
Savepoints: NO
*************************** 8. row ***************************
Engine: InnoDB
Support: DEFAULT
Comment: Supports transactions, row-level locking, and foreign keys
Transactions: YES
XA: YES
Savepoints: YES
*************************** 9. row ***************************
Engine: PERFORMANCE_SCHEMA
Support: YES
Comment: Performance Schema
Transactions: NO
XA: NO
Savepoints: NO
mysql Support nine storage engines , At present 5.5.36 Support 8 individual . Different versions support different situations .
8.4. About mysql Common storage engines , A brief introduction
8.4.1. MyISAM Storage engine
The tables it manages have the following characteristics , Use three files to represent each table :
- Format file — Definition of storage table structure (mytable.frm)
- Data files — Store the contents of table rows (mytable.MYD)
- Index file — Store indexes on tables (mytable.MYI): The index is the catalogue of a book , Narrow the scanning range , A mechanism to improve query efficiency . Can be converted to compressed 、 Read only tables to save space
Hint :
For a table , As long as it's a primary key , Or add unique An index is automatically created on the constrained field .
8.4.2. MyISAM Storage engine
Can be converted to compressed 、 Read only tables to save space , This is the advantage of this storage engine !!!!
MyISAM Transaction mechanism is not supported , Low security .
8.4.3. InnoDB Storage engine
This is a mysql The default storage engine , It is also a heavyweight storage engine .
InnoDB Support transactions , Support automatic recovery mechanism after database crash .InnoDB The main feature of the storage engine is : Very safe .
The tables it manages have the following main characteristics :
- Every InnoDB The table is in the database directory as .frm The format file represents
- InnoDB Table space tablespace Used to store the contents of a table ( A tablespace is a logical name . Tablespaces store data + Indexes .)
- Provides a set of log files used to record transactional activities
- use COMMIT( Submit )、SAVEPOINT And ROLLBACK( Roll back ) Support transaction processing
- Provide full ACID compatible
- stay MySQL Provide automatic recovery after server crash
- Many versions (MVCC) And row level locking
- Support the integrity of foreign keys and references , Including cascading deletion and update
InnoDB The biggest feature is to support transactions :
To ensure data security . Not very efficient , And can't compress , Cannot convert to read-only , It can't save storage space well .
8.4.4. MEMORY Storage engine
Use MEMORY The table that stores the engine , Its data is stored in memory , And the length of the line is fixed , These two characteristics make MEMORY The storage engine is very fast .
MEMORY The tables managed by the storage engine have the following characteristics :
- In the database directory , Each table is marked with .frm Format file representation .
- Table data and indexes are stored in memory .( The goal is to , Quick query !)
- Table level locking mechanism .
- Can not contain TEXT or BLOB Field .
MEMORY The storage engine was formerly known as HEAP engine .
MEMORY Engine benefits : The query efficiency is the highest . No need to interact with the hard disk .
MEMORY Engine faults : unsafe , The data disappears after shutdown . Because the data and index are in memory .
9. Business ( a key : Five stars *****, Must understand , Must master )
9.1. What is business ?
A transaction is actually a complete business logic . Is the smallest unit of work . Can not be further divided .
What is a complete business logic ?
Hypothetical transfer , from A Account to B Transfer from account 10000, take A The money in the account minus 10000(update sentence ), take B The money in the account plus 10000(update sentence ), This is a complete business logic .
The above operation is the smallest unit of work , Or at the same time , Or fail at the same time , Can not be further divided .
these two items. update Statement requires both success and failure , In this way, we can ensure that the money is right .
9.2. Only DML Statement will have the statement of transaction , Other statements have nothing to do with transactions
insert
delete
update
Only the above three statements are related to transactions , Nothing else matters .
Because only the above three statements are added to the data in the database table 、 Delete 、 Changed , As long as your operation involves the increase of data 、 Delete 、 Change , Then we must consider the safety issue .
Data security comes first !!!
9.3. Suppose all businesses , Just one DML Statement can be completed , Is it necessary to have a transaction mechanism ?
Because when you do something , Multiple lines are required DML Statements can be combined to complete , Therefore, we need the existence of transactions . If anything complicated can be done in one way DML Statement handling , Then the transaction has no value of existence .
What exactly is a business ?
At the end of the day , Speaking of essence , A transaction is actually multiple DML Statements succeed at the same time , Or fail at the same time !
Business : It's batch DML Statements succeed at the same time , Or fail at the same time !
9.4. How to do multiple transactions DML What about statements that succeed and fail at the same time ?
InnoDB Storage engine : Provides a set of log files used to record transactional activities
The transaction is on
insert
insert
delete
delete
update
update
The business is over !
During the execution of a transaction , Every one of them DML All operations will be recorded in “ Log files for transactional activities ” in .
During the execution of a transaction , We can commit transactions , Transactions can also be rolled back .
9.4.1. Commit transaction ?
Clear the log file of transactional activities , Completely persist all data into database tables .
Committing a transaction marks , The end of the business . And it's the end of all success .
9.4.2. Roll back the transaction ?
All the previous DML Undo all operations , And clear the log files of transactional activities
Rolling back a transaction marks , The end of the business . And it's the end of all failure .
9.5. How to commit transactions , How to roll back a transaction ?
Commit transaction :commit; sentence
Roll back the transaction :rollback; sentence ( Rollback can only be rolled back to the last commit point !)
The English word for a transaction is :transaction
Test it , stay mysql What is the default transaction behavior ?
mysql Automatic transaction submission is supported by default .( Automatic submission )
9.5.1. What is auto submit ?
Every time you execute one DML sentence , Then submit once !
This automatic submission is actually not in line with our development habits , Because a business usually needs multiple DML Statements can be executed together , To ensure data security , You must ask for success before submitting , So you can't execute one and submit one .
9.5.2. How to mysql The automatic submission mechanism is turned off ?
start transaction;
...
commit
9.5.3. Roll back the transaction
mysql> use bjpowernode;
Database changed
mysql> select * from dept_bak;
Empty set (0.00 sec)
mysql> start transaction;
Query OK, 0 rows affected (0.00 sec)
mysql> insert into dept_bak values(10,'abc', 'tj');
Query OK, 1 row affected (0.00 sec)
mysql> insert into dept_bak values(10,'abc', 'tj');
Query OK, 1 row affected (0.00 sec)
mysql> select * from dept_bak;
+--------+-------+------+
| DEPTNO | DNAME | LOC |
+--------+-------+------+
| 10 | abc | tj |
| 10 | abc | tj |
+--------+-------+------+
2 rows in set (0.00 sec)
mysql> rollback;
Query OK, 0 rows affected (0.00 sec)
mysql> select * from dept_bak;
Empty set (0.00 sec)
9.5.4. Commit transaction
mysql> use bjpowernode;
Database changed
mysql> select * from dept_bak;
+--------+-------+------+
| DEPTNO | DNAME | LOC |
+--------+-------+------+
| 10 | abc | bj |
+--------+-------+------+
1 row in set (0.00 sec)
mysql> start transaction;
Query OK, 0 rows affected (0.00 sec)
mysql> insert into dept_bak values(20,'abc', 'tj');
Query OK, 1 row affected (0.00 sec)
mysql> insert into dept_bak values(20,'abc','tj');
Query OK, 1 row affected (0.00 sec)
mysql> insert into dept_bak values(20,'abc','tj');
Query OK, 1 row affected (0.00 sec)
mysql> commit;
Query OK, 0 rows affected (0.01 sec)
mysql> select * from dept_bak;
+--------+-------+------+
| DEPTNO | DNAME | LOC |
+--------+-------+------+
| 10 | abc | bj |
| 20 | abc | tj |
| 20 | abc | tj |
| 20 | abc | tj |
+--------+-------+------+
4 rows in set (0.00 sec)
// Cannot roll back after commit
mysql> rollback;
Query OK, 0 rows affected (0.00 sec)
mysql> select * from dept_bak;
+--------+-------+------+
| DEPTNO | DNAME | LOC |
+--------+-------+------+
| 10 | abc | bj |
| 20 | abc | tj |
| 20 | abc | tj |
| 20 | abc | tj |
+--------+-------+------+
4 rows in set (0.00 sec)
9.6. The business includes 4 A feature ?
9.6.1. A: Atomicity
It shows that transaction is the smallest unit of work . Can not be further divided .
9.6.2. C: Uniformity
All transactions require , In the same transaction , All operations must be successful at the same time , Or fail at the same time , To ensure data consistency .
9.6.3. I: Isolation,
A Business and B There is some isolation between transactions . classroom A And classroom B There is a wall between , This wall is isolation .
A When a transaction operates on a table , Another business B What will happen if you also operate this table ? See later
9.6.4. D: persistence
One guarantee for the final end of a transaction is the transaction commit , It is equivalent to saving data that has not been saved to the hard disk
Save to hard disk !
9.7. Focus on the isolation of transactions
A Classroom and B There is a wall in the middle of the classroom , This wall can be very thick , It can also be very thin . This is the isolation level of the transaction .
The thicker the wall , Indicates that the higher the isolation level .
What are the isolation levels between transactions ?4 A level
9.7.1. Read uncommitted :read uncommitted( Lowest isolation level )《 Did not submit to read 》
What is read uncommitted ? Business A Can read to transaction B Uncommitted data .
The problem with this isolation level is : Dirty reading !(Dirty Read), We said we read dirty data .
This level of isolation is generally theoretical , Most database isolation levels are second-class !
9.7.2. Read submitted :read committed《 You can't read... Until you submit it 》
What is read committed ? Business A Only transactions can be read B Data after submission .
What problem does this isolation level solve ? Solved the phenomenon of dirty reading .
What's wrong with this level of isolation ? Data cannot be read repeatedly .
What is unrepeatable data ? After the transaction is opened , The first data read is 3 strip , The current transaction is not over yet , Maybe the second time I read it again , The data read is 4 strip ,3 It's not equal to 4 It is called non repeatable read .
This level of isolation is more real data , The data read every time is absolutely true .
oracle The default isolation level of the database is :read committed
9.7.3. Repeatable :repeatable read《 I can't read it after submitting it , Always read the data when the transaction was just started 》
What is a repeatable read ? Business A After opening , No matter how long , Every time in business A The data read in is consistent , Even if the business B The data has been modified , And submitted , Business A The read data still hasn't changed , This is repeatable reading .
What problem does repeatable reading solve ? It solves the problem of non repeatable data reading .
What are the problems with repeatable reading ? There can be phantom reading . Every time the data is read, it is an illusion . Not true enough !
In the morning 9 The transaction started at , As long as the business doesn't end , until night 9 spot , The data read is still like that ! What I read is an illusion . Not absolutely true .
mysql This is the default transaction isolation level in !!!!!!!!!!!
9.7.4. Serialization :serializable( Highest isolation level )
This is the highest isolation level , Minimum efficiency . Solved all the problems .
This isolation level indicates that transactions are queued , Can't be concurrent ! Efficiency is the lowest .
9.8. Check the isolation level
// 5.x edition
SELECT @@tx_isolation;
+-----------------+
| @@tx_isolation |
+-----------------+
| REPEATABLE-READ |
+-----------------+
// 8.x edition
SELECT @@transaction_isolation;
+-------------------------+
| @@transaction_isolation |
+-------------------------+
| REPEATABLE-READ |
+-------------------------+
9.9. Set the isolation level
// set global transaction isolation level + Isolation level ;
set global transaction isolation level read uncommitted;
9.10. Examples of various isolation levels
9.10.1. Read uncommitted read uncommited
mysql> set global transaction isolation level read uncommitted;
Business A Business B
--------------------------------------------------------------------------------
use bjpowernode;
use bjpowernode;
start transaction;
select * from t_user;
start transaction;
insert into t_user values('zhangsan');
select * from t_user;
9.10.2. Read submitted read commited
mysql> set global transaction isolation level read committed;
Business A Business B
--------------------------------------------------------------------------------
use bjpowernode;
use bjpowernode;
start transaction;
start transaction;
select * from t_user;
insert into t_user values('zhangsan');
select * from t_user;
commit;
select * from t_user;
9.10.3. Repeatable repeatable read
mysql> set global transaction isolation level repeatable read;
Business A Business B
--------------------------------------------------------------------------------
use bjpowernode;
use bjpowernode;
start transaction;
start transaction;
select * from t_user;
insert into t_user values('lisi');
insert into t_user values('wangwu');
commit;
select * from t_user;
9.10.4. Serialization serializable
mysql> set global transaction isolation level serializable;
Business A Business B
--------------------------------------------------------------------------------
use bjpowernode;
use bjpowernode;
start transaction;
start transaction;
select * from t_user;
insert into t_user values('abc');
select * from t_user;
10. download
10.1. This document
https://hty.ink/down/mysql/day_3.zip
10.2. Information involved
https://hty.ink/down/mysql/ziliao.zip
11. Read on
11.1. Last one
11.2. Next
边栏推荐
- Tidb v6.0.0 (DMR): initial test of cache table - tidb Book rush
- Rendering engine development
- Redis design and Implementation (II) | database (deletion strategy & expiration elimination strategy)
- Redis design and Implementation (VII) | publish & subscribe
- [JUC series] overview of fork/join framework
- Gilbert Strang's course notes on linear algebra - Lesson 1
- Build a docker image of Henkel database from 0
- Circuit analysis of current probe
- 亚马逊测评术语有哪些?
- QT event cycle
猜你喜欢

Self made GIF dynamic graph -gifcam

TiDB 6.0:让 TSO 更高效丨TiDB Book Rush

Enhance the add / delete operation of for loop & iterator delete collection elements

Redis设计与实现(八)| 事务

Gilbert Strang's course notes on linear algebra - Lesson 3

【NVMe2.0b 14-2】Create/Delete Queue

Redis design and Implementation (VIII) | transaction

【NVMe2.0b 14-1】Abort、Asynchronous Event Request、Capacity Management command

Sword finger offer II 075 Array relative sort (custom sort, count sort)

C # about Net cognition
随机推荐
Tidb 6.0: making Tso more efficient tidb Book rush
PHP API to obtain QR code and combine to generate pictures
Niuke White Moon race 52
Cesium learning notes (IV) visual image & Terrain
How can we get a satisfactory salary? These routines still need to be mastered
Experiment 4 QT
Graffiti Wi Fi & ble SoC development slide strip
CUDA realizes L2 European distance
Redis设计与实现(八)| 事务
Enter the URL in the browser and display it on the page
codeforces每日5题(均1700)-第三天
Redis design and Implementation (III) | interaction between server and client (event IO model)
Implementation of remote monitoring by camera in Experiment 5
Redis设计与实现(五)| Sentinel哨兵
C# ListBox如何获取选中的内容(搜了很多无效的文章)
Unity basic lighting model
Is the reverse repurchase of treasury bonds absolutely safe? How to open an account online
挖财开户安全吗?怎么有人说不靠谱。
Tidb v6.0.0 (DMR): initial test of cache table - tidb Book rush
Cesium learning notes (III) creating instances