当前位置:网站首页>MySQL day03 class notes
MySQL day03 class notes
2022-06-22 04:58:00 【Vision patient Leon】
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
First of all : In actual development , Once the requirements are determined , Once the watch is designed , Very few
Modify 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 !
second : Because there are few operations to modify the table structure , So we don't need to master , If one day
Really want to change the table structure , 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 that the data in this table
integrity 、 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
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 | [email protected] |
| 2 | lisi | [email protected] |
| 3 | wangwu | [email protected] |
| 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 in line with my “ The new demand ” Of .
But if you create a table in the above way , Definitely failed to create , because 'zhangsan' and 'zhangsan' repeated .
insert into t_vip(id,name,email) values(1,'zhangsan','[email protected]');
insert into t_vip(id,name,email) values(2,'zhangsan','[email protected]');
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 *****
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 .
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 !)
How to add a primary key constraint to a table ?
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, // Column level constraints
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
Can I add a primary key like this , Use table level constraints ?
drop table if exists t_vip;
create table t_vip(
id int,
name varchar(255),
primary key(id) // Table level constraints
);
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'
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 !!!
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 !
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 !
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 .
stay mysql among , There is a mechanism , It can help us maintain a primary key value automatically ?
drop table if exists t_vip;
create table t_vip(
id int primary key auto_increment, //auto_increment Said the increase , from 1 Start , With 1 Increasing !
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 *****
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 .
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 2 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 .
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 .
drop table if exists t_student;
drop table if exists t_class;
create table t_class(
classno int primary key,
classname varchar(255)
);
create table t_student(
no int primary key auto_increment,
name varchar(255),
cno int,
foreign key(cno) references t_class(classno) // Add a foreign key constraint
);
insert into t_class(classno, classname) values(100, ' Senior 3, No. 2 middle school, Yizhuang Town, Daxing District, Beijing 1 class ');
insert into t_class(classno, classname) values(101, ' Senior 3, No. 2 middle school, Yizhuang Town, Daxing District, Beijing 2 class ');
insert into t_student(name,cno) values('jack', 100);
insert into t_student(name,cno) values('lucy', 100);
insert into t_student(name,cno) values('lilei', 100);
insert into t_student(name,cno) values('hanmeimei', 100);
insert into t_student(name,cno) values('zhangsan', 101);
insert into t_student(name,cno) values('lisi', 101);
insert into t_student(name,cno) values('wangwu', 101);
insert into t_student(name,cno) values('zhaoliu', 101);
select * from t_student;
select * from t_class;
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 .
test : Foreign key can be NULL Do you ?
The foreign key value can be NULL.
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 .
Conclusion :
mysql The default storage engine is :InnoDB
mysql 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 Introduce the common storage engines
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 .
MyISAM Storage engine features :
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 .
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 .
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 add 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
insert
delete
update
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 .
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 .
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 )
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 of a business
It usually requires more than one DML Statements can be executed together , In order to guarantee the data
The safety of the , You must ask for success before submitting , So you can't execute one
Just submit one .
How to mysql The automatic submission mechanism is turned off ?
Execute this order first :start transaction;
Demonstrate transaction :
--------------------------------- 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)
--------------------------------- 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
Query OK, 1 row affected (0.00 sec)
mysql> insert into dept_bak values(20,'abc
Query OK, 1 row affected (0.00 sec)
mysql> insert into dept_bak values(20,'abc
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)
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 ?
A: Atomicity
It shows that transaction is the smallest unit of work . Can not be further divided .
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 .
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 If you also operate this table, it will be like that ???
D: persistence
A guarantee of the end of the transaction . Transaction submission , 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
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 !
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 has not yet
end , 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
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 Data read from
It's all 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 !!!!!!!!!!!
serialize / 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 !
synchronized, Thread synchronization ( Transaction synchronization )
The data read every time is the most real , And the efficiency is the lowest .
9.8、 Verify various isolation levels
Check the isolation level :SELECT @@tx_isolation
±----------------+
| @@tx_isolation |
±----------------+
| REPEATABLE-READ |
±----------------+
mysql Default isolation level
The table being tested t_user
verification :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;
verification :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;
verification :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;
verification :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;
边栏推荐
- 【故障诊断】使用多线程,程序不报错,但就是不运行
- 使用Chrome调试微信内置浏览器
- NLP 的 不可能三角?
- Graph calculation on nlive:nepal's graph calculation practice
- ORA-15063: ASM discovered an insufficient number of disks for diskgroup 恢複---惜分飛
- LeetCode——二叉搜索树的第k大节点(借助中序遍历)
- Golang為什麼不推薦使用this/self/me/that/_this
- Progress warning and problem management of progress control in Zhiyuan project management SPM system
- In 2022, the super intern plans to make a breakthrough in the offer of it famous enterprises, and the nine high salary skills help the dream of famous enterprises
- mysql常用sql
猜你喜欢

Web page design and production final assignment report - College Students' online flower shop

Overrides vs overloads of methods

LeetCode——二叉搜索树的第k大节点(借助中序遍历)

Researcher of Shangtang intelligent medical team interprets organ image processing under intelligent medical treatment

The best time to climb a ladder & sell shares (notes of the runner)

【故障诊断】CUDA kernel errors might be asynchronously reported at some other API call,so the stacktrace b

Arrangement of soft test subjects in the second half of 2022
![[scientific research notes] focal loss](/img/ca/4a30fd925b87ed2baa2523d8dbf59d.png)
[scientific research notes] focal loss

【故障诊断】stitch.py脚本失效

软考2022年下半年考试科目安排
随机推荐
【SDX62】IPA log抓取操作说明
Kotlin项目报错缺少CoroutineContext依赖
厉害了!淮北两企业获准使用地理标志产品专用标志
Using Matplotlib to realize GUI interaction effect
The feeling of leaving full-time for a single month!
Compilation des connaissances communes de la base de données numpy
VirtualBox 6.1.34 release
Accurate identification of bank card information - smart and fast card binding
Go learning (I. Basic Grammar)
MySQL notes
NLP 的 不可能三角?
Cloud native enthusiast weekly: Chaos mesh upgraded to CNCF incubation project
Final examination questions of Database Principles
[sdx62] IPA log fetching instructions
[sdx12] use qcmap_ CLI startup WiFi operation instructions
ORA-15063: ASM discovered an insufficient number of disks for diskgroup 恢複---惜分飛
The application of RPC technology and its framework sekiro in crawler reverse, encrypting data is a shuttle!
mongo模糊查詢,帶有特殊字符需要轉義,再去查詢
Knowledge points used in MVC project development (mvccontrib separates asp.net MVC project)
mysql day04课堂笔记