Article directory
- foreword
- 1. ER model
- 2. Data type
- 3. Field naming convention
- 4. Database creation and management
- 5. Data table creation and management
-
- 5.1, create table, structure
- 5.2. View table structure
- 5.3, view the data table
- 5.4. Copy table structure
- 5.5. Copy table data
- 5.6. Modify the table name
- 5.7. Add fields
- 5.8, delete field
- 5.9. Modify the data type of the field
- 5.10. Modify the name of the field
- 5.11, set the primary key
- 5.12, delete the primary key
- 5.13, foreign key
- 5.14. Delete foreign key
- 6. Data update
- 7. Data query
- 8. Index
- 9. View
- 10. Stored procedure
- 11. Basics of SQL Programming
- 12. Trigger
- 13. Affairs
- 14. User management and rights management
- 15. Backup and restore database
- 16. Log
- Summarize
foreword
Hello everyone, I am Qiu Yilin.
The semester is coming to an end. Before the end, I will summarize an article on MySQL. It has a lot of space and content, so it is a collection-level article, because the content coverage is relatively wide, relatively shallow, and easy to understand. It is very suitable for novices who are learning mysql . It can be used as a msyql command manual Daquan, covering all the basic operations of mysql (I believe you will understand it when you see the directory structure).
Always look new, always look new, always look new! ! ~
Remember to bookmark + pay attention so as not to get lost.
Welcome to the cloud community
1. ER model
The entity-relationship model (ER model for short) provides a user-oriented expression method that is not bound by any DBMS, and is widely used as a data modeling tool in database design.
When we are working on a project, we need to use the ER model to draw the ER diagram in advance, so that the database structure is clear and reasonable.
A constraint in a DBMS that enforces restrictions on the data or types of data that can be inserted, updated, or deleted from a table. The whole purpose of constraints is to maintain data integrity while updating, deleting, inserting into a table.
type of constraint
- not-null, unique, default, validation, key constraints – primary key, foreign key, domain constraint, map constraint
2. Data type
3. Field naming convention
1. It is composed of 26 English letters (case-sensitive) and natural numbers from 0-9 (often not needed) plus an underscore _'. The name is concise and clear, and multiple words are separated by an underscore _'.
2. Generally use lowercase naming.
3. It is forbidden to use database keywords, such as: table, time, datetime, primary, etc.
4. Field names generally use nouns or verb-object phrases, such as user_id, is_good.
5. The name of the field used must be easy to understand, generally no more than three English words.
4. Database creation and management
help
illustrate:
- table_name: data table table name
col_name: field name
data_type: data type of the field
View the creation process
grammar:show create 关键字(table database) 名称;
show create table t_teacher;
4.1. Create database
grammar:create database db_name;
create database db_test;
4.2, delete the database
grammar:drop database db_name;
drop database db_test;
4.3. List databases
grammar:show databases;
show databases;
4.4, backup database
If operating on the host machine, the -h parameter can be omitted.
grammar:mysqldump -h 主机名 -u 用户名 -p 密码 数据库名称 > 脚本文件路径;
mysqldump -uroot -p000000 test > test.sql;
4.5. Restoring the database
grammar:mysql -h 主机名 -u 用户名 -p 密码 数据库名称 < 脚本文件路径;
mysql -uroot -p000000 test < test.sql;
或者
source test.sql;
4.6. Using a certain database
grammar:use db_name;
use db_test;
5. Data table creation and management
5.1, create table, structure
Syntax: create table table_name(col_name1 data_type1,col_name2 data_type2,....);
Create a t_test data table, the field is id, name (the number in the data type is the field length)
create table t_test(id char(20),name char(10));
5.2. View table structure
grammar:describe table_name;
desc table_name;
describe can be abbreviated as desc.
describe t_test;
desc t_test;
5.3, view the data table
grammar:show tables;
show tables;
5.4. Copy table structure
If you are copying the table structure of another database, add the name of the database before table_name2
grammar:create table new_table_name1 like old_table_namme2;
Copy the t_test1 table structure in the database db_test to the current database, and name it as the table structure t_test2.
create table t_test1 like t_test2;
5.5. Copy table data
consistent table structure
insert into table_name_new select * from table_name_old;
Inconsistent table structure
insert into table_name_new(column1,column2...) select column1,column2... from table_name_old;
5.6. Modify the table name
grammar:alter table old_table_name (旧名字) rename new_table_name(新名字);
alter table t_test1 rename t_test2;
5.7. Add fields
grammar:alter table table_name add col_name1(添加字段名)data_type (字段类型);
alter table t_test add test_address varchar(255);
5.7.1. Put the added field first
grammar:alter table table_name add col_name1(添加字段名)data_type (字段类型) first;
alter table t_test add test_address varchar(255) first;
5.7.2. Put the added field after the test2 field
grammar:alter table table_name add col_name1(添加字段名)data_type (字段类型) after test2(字段);
alter table t_test add test1 varchar(20) after test2;
5.8, delete field
grammar:alter table t_reader drop reader_qq (删除的字段名);
alter table t_test drop test1;
5.9. Modify the data type of the field
Syntax: alter table table_name modify col_name1(字段名) data_type (字段类型);
Change the data type of test2 from varchar to char.
alter table table_name modify test2 char(100);
5.10. Modify the name of the field
grammar:alter table table_name change old_col_name(字段名) new_col_old(新字段名) data_type(字段数据类型);
alter table t_test change test_address address char(100);
5.11, set the primary key
Role: to ensure the uniqueness of the input record
. Method:
- set when creating the table
- Set after table creation
Syntax: create table table_name(xs_id char(12),xs_name char(10) primary key (xs_id));
When creating the studnet table, set xs_id as the primary key.
create table student (xs_id char(12),xs_name char(10),primary key(xs_id));
When creating studnet table, set xs_id and xs_name as primary key. This way of setting multiple fields as the primary key is called: composite primary key. A composite primary key is also a primary key (uniqueness).
create table student (xs_id char(12),xs_name char(10),primary key(xs_id,xs_name));
5.12, delete the primary key
语法:alter table table_name drop primary key;
alter table studnet drop primary key;
5.13, foreign key
Role: to ensure data integrity. like:
- entity integrity
- User Defined Integrity
- Referential integrity
Only after a field becomes a primary key can it become a foreign key in another table.
grammar:alter table table_name add constraint 外键名称 foreign key (设为外键的字段名)references t_table2(主键字段名);
Set the id field in the t_test1 table as the primary key, and the id field in the t_test2 table as the foreign key.
alter table t_test2 add constraint fk1 foreign key (id) references t_test1(id);
5.14. Delete foreign key
Syntax: show create table table_name;
Get the foreign key name:
show create table t_test2;
grammar:alter table t_test2 drop foreign key 外键名称;
alter table t_test2 drop foreign key fk1;
6. Data update
6.1, insert insert record
6.1.1. Insert a single record
grammar:insert [into] 表名 [字段1,字段n] values(值1,值n);
insert into test values(123,'tt');
insert into test(pid) values(124);
6.1.2. Insert multiple records
insert into test values(125,'ttww'),(126,'ttwwe'),(127,'ttqqq');
6.1.3, sub query, insert multiple records
Use the content field queried by select to insert it into the field corresponding to inert
grammar:insert [into] 表名1 [字段1,字段n] select [字段1,字段n] from 表名2 [where语句];
insert into test-1 select * from test-2;
insert into test-1(pid,name) select pid,name from test-2;
6.2, delete delete records
grammar:delete from 表名 [where <条件>];
delete from test; ## 删除所有记录
delete from test where pid==123; #删除id为123的这条记录。
6.3, update update record
grammar:update 表名 set 列名1 = 值1,列名2 = 值2,…[where 条件];
7. Data query
7.1. Single table query
1. Syntax: select <[列名1,列名n 或通配符 [as 别名] ]> from 表名;
as: alias a field
2. Grammar: select distinct <[列名1,列名n 或通配符]> from 表名;
Remove duplicates, add before the corresponding field
Symbolic expression:
7.1.1, where common keywords
- AND, OR: Connect multiple conditions
BETWEEN AND: Between
IS NULL: Query for null values
IN: Query in a certain set
LIKE: Fuzzy query
7.1.2. Wildcards
"*" wildcard: match any column name
"_" wildcard: match a single character
"%" wildcard: match any character
7.1.3, order by child clause
You can use the order by clause to install one or more attribute columns (multiple attributes separated by commas) in ascending (ASC) or descending (DESC) order, and the default is ascending.
--查询结果按照bookPrice列值的降序排列
select * from books order by bookPrice desc;
7.1.4. Aggregate functions
example:
#查询book表中年龄最大的
select max(age) from book;
7.1.5, group by child clause
Group the query results by the values of one or more columns, and the values are equal as a group.
select count(*),pressName from books group by pressName;
For example: In the following list, there is 1 name named "People's Posts and Telecommunications Press", and 6 names named "Tsinghua University Press".
7.2. Connection query
Query data according to the relationship between the columns of two tables or multiple tables, that is, join query.
7.2.1. Simple connection
Connection query is actually a data query through the columns related to each other between tables. For relational databases, connection is the most important feature of query.
Simple joins use commas to join two or more tables and are the most commonly used form of multi-table queries.
example:
select b.reader_id,br.book_name from books b,borrow_record br where b.ISBN=br.ISBN;
7.2.2, JOIN connection
In addition to using commas to connect, you can also use JOIN to connect.
7.2.2.1, inner join (inner join)
1) Equivalent connection
select * from books b inner join borrow_record br where b.ISBN=br.ISBN;
2) Unequal connection
select * from books b inner join borrow_record br where b.ISBN<>br.ISBN;
7.2.2.2, outer join (left join, right join)
1) You can also use where to execute conditional judgment after left join on
select * from books b left join borrow_record br on b.ISBN=br.ISBN;
2)
You can also use where to execute conditional judgment after the right connection on
select * from books b right join borrow_record br on b.ISBN=br.ISBN;
7.3. Nested query
In the SQL language, a select-from-where statement is called a query block . Queries that nest one query block within the conditions of another query block's where clause or having phrase are called nested queries .
grammar:select <字段名或通配符> from <表或视图名> where [表达式] (select <字段名或通配符> from <表或视图名> where [表达式] )
7.3.1. Subqueries with IN predicates
select * from books where isbn in (select * isbn from brrowrecord where reader_id='201801');
7.3.2. Subqueries with comparison operators
Refers to the connection between the parent query and the subquery using a comparison operator. You can use comparison operators such as >, <, =, >=, <=, !=, <>, etc.
select * from books where isbn=(select * isbn from brrowrecord where reader_id='201801');
7.3.3. Subqueries with ANY (SOME) or ALL predicates
When a subquery returns a single value, a comparison operator can be used, but when multiple values are returned, the ANY (some systems use SOME) or ALL predicate must be used. When using the ANY or ALL predicate , a comparison operator must be used at the same time .
Predicate interpretation:
Example:
#查询读者编号为"201801"的学生未借阅的所有图书的详细信息;
select * from books where isbn <> all(select isbn from brrowwrecord where reader_id="201801");
7.3.4. Subquery with EXISTS predicate
The subquery of the EXISTS predicate does not return any data and is a Boolean (true or false) logical judgment. After using the existential quantifier EXISTS, if the inner query result is empty, the outer WHERE clause returns true, otherwise it is negated.
example:
#查询读者编号为201801的读者没有借阅过的图书信息
select * from books where not exists (select * from borrowrecord where isbn=books.isbn and reader_id="201801");
7.4. Combine query
#两个表字段合并显示,两个表相同字段合并后显示一次
select * from t_major1 union select * from t_major;
8. Index
An index is a decentralized storage structure created to speed up the retrieval of data rows in a table .
8.1. Create an index for the created table
1) Use the CREATE INDEX method to create an ordinary descending index for its field name stu_id on the already created table t_student.
Syntax: create [unique | fulltext] index index_name on table_name(co_name ase|desc , [co_name ase|desc] )
#Multi-field indexes are separated by commas (,)
create index index_student on t_student(stu_id desc)
2) Use the ALTER TABLE...ADD INDEX method to create a full-text index for the field column course_name of the table t_course.
Syntax: alter table table_name add [unique | fulltext] index index_name(co_name ase|desc , [co_name ase|desc] )
#Multi-field indexes are separated by commas (,)
alter table t_course add fulltext index index_course_name(course_name)
8.2. Create an index when creating a new table
Create the table t_teacher2, which is consistent with the structure of t_teacher (the table structure cannot be copied), create an index during the table creation process, and create a unique ascending index for teacher_id.
create table t_teacher2(teacher_id char(10),teacher_name char(50),index index_tea_id(teacher_id asc));
9. View
View (View) is actually a table derived from one or more relational tables (or views). It is a virtual table similar to a soft link.
9.1, create a view
Create a view view_basic_info, the data comes from the t_student table
Syntax:create view <视图名> as select_statement
create view view_basic_info as select * from t_student;
9.2, modify the view
grammar:create view <视图名> as select_statement
alter view view_basic_info as select * from t_student;
9.3, delete view
drop view view_basic_info;
10. Stored procedure
The stored procedure is very similar to the function in the program. It can write some code segments that need to be called multiple times to achieve a specific task into a procedure , save it in the database, and call it by the procedure name. These procedures are called for the stored procedure.
DELIMITER Definition: Set the delimiter used after the end of the statement, the default terminator of MYSQL is ";".
10.1. Create a stored procedure
mysql> delimiter $
mysql> create procedure p1()
-> comment '读者信息'
-> begin
-> select * from t_reader;
-> end $
mysql> delimiter ;
10.2. Call stored procedure
mysql> call p1;
10.3. Delete stored procedure
mysql> drop procedure p1;
10.4. Create a stored procedure with parameters
10.4.1、in
- Create a stored procedure with input parameters to query the student information corresponding to a certain student number.
mysql> delimiter $
mysql> create procedure p3(in stuid char(10))
comment "查询某个学号对应的学生信息"
begin
select * from t_student where stu_id=stuid;
end $
mysql> delimiter ;
mysql> call p3(1631607102); #调用存储过程
10.4.2、out
- Create a stored procedure with an output parameter to query the number of all students.
Note: Adding @ before the variable name means: session variable
session variable: not limited to the inside of the stored procedure
mysql> delimiter $
mysql> create procedure p6(out stucount int)
begin
select COUNT(stu_id) into stucount from t_student;
end $
mysql> delimiter ;
mysql> call p6(@stucount); #调用存储过程
mysql> select @stucount; #查看输出变量
10.4.3、inout
- Create a stored procedure with input and output parameters to add 20 points to a certain grade.
mysql> delimiter $
mysql> create procedure p9(inout testname int)
begin
update t_score set grade=grade+20 where score_id=testname;
select grade into testname from t_score where score_id=testname;
end $
mysql> delimiter ;
mysql> set @testname=1001;
mysql> call p9(@testname);
mysql> select @testname;
@pra: session variables are not restricted to inside stored procedures
11. Basics of SQL Programming
11.1, SQL programming basic syntax
SQL is essentially a programming language that requires variables to store data. Many attribute controls in MySQL are implemented through variables in MySQL.
Variables are divided into two categories: system variables and user variables ;
System variables: effective for all users, that is, all clients in MySQL.
User variable: for specifying the corresponding user.
11.1.1. System variables
MySQL system variables are actually used to store system parameters, and are used to initialize and set MySQL’s occupation of system resources, storage locations of configuration files, and so on. Most variables exist as adjustment parameters of the MySQL system, and modifying these parameters will affect the operation mode of MySQL.
System variables: divided into global (global) variables and session (session) variables.
Global variables: affect the overall operation of the entire MySQL instance.
Session variables: affect the current connection to the MySQL instance.
11.1.1.1. View system variables
11.1.1.1.1, session variables and global variables
grammar:show variables 条件语句
Condition statement: represents the filter condition to query the system variable (optional)
View all system variables; session variables first, global variables second.
show variables; //查看所有系统变量
Limit the scope of system variables through the global and session keywords.
show global variables; //查看全局变量
show session variables; //查看会话变量
If you want to view some specific system variables, but not all, you can use like and where statements:
show variables like 'log%'; //查询所有变量名以log开头的系统变量
If in the query, in addition to the variable name condition, the value condition is also used in the condition, you can use the where statement:
show variables where variable_name like 'log%' and value='OFF';
11.1.1.1.2, configuration variables and monitoring variables
MySQL system variables can also be divided into: configuration variables and monitoring variables
show variables; // 查看配置变量
show status; // 查看监控变量
Similarly, if you want to add conditional statements when querying system status variables, the method is the same as when querying configuration variables.
11.1.1.2, common system variables
In the work, the database is generally divided into "development library", "test library", "online library" and other environments.
View current MySQL version information
mysql> show variables like 'version%';
+-------------------------+------------------------------+
| Variable_name | Value |
+-------------------------+------------------------------+
| version | 8.0.30 |
| version_comment | MySQL Community Server - GPL |
| version_compile_machine | x86_64 |
| version_compile_os | Win64 |
| version_compile_zlib | 1.2.12 |
+-------------------------+------------------------------+
5 rows in set, 1 warning (0.02 sec)
Maximum number of connections
When connecting to the database, you often
MySQL: ERROR 1040: Too many connections
encounter error messages. One situation is that MySQL cannot handle it because of too much access. At this time, the number of 'slave' servers can be increased to ease the pressure of 'reading'. Another situation is thatmax_connections
the value is set too small.
mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 200 |
+-----------------+-------+
1 row in set, 1 warning (0.00 sec)
current connections
Only then
Threads_connected <= max_connections
can the normal connection to the database be guaranteed.
mysql> show status like 'Threads_connected';
+-------------------+-------+
| Variable_name | Value |
+-------------------+-------+
| Threads_connected | 1 |
+-------------------+-------+
1 row in set (0.00 sec)
MySQL encoding configuration information
If the problem of Chinese garbled characters occurs, it is usually caused by inconsistent MySQL encoding settings.
mysql> show variables like '%set%';
+---------------------------------------+---------------------------------------------------------------+
| Variable_name | Value |
+---------------------------------------+---------------------------------------------------------------+
| auto_increment_offset | 1 |
| character_set_client | utf8mb4 |
| character_set_connection | utf8mb4 |
| character_set_database | utf8mb4 |
| character_set_filesystem | binary |
| character_set_results | utf8mb4 |
| character_set_server | utf8mb4 |
| character_set_system | utf8mb3 |
| character_sets_dir | D:\APP\Pro_Software\MYSQL\mysql-8.0.30-winx64\share\charsets\ |
| innodb_monitor_reset | |
| innodb_monitor_reset_all | |
| optimizer_trace_offset | -1 |
| performance_schema_setup_actors_size | -1 |
| performance_schema_setup_objects_size | -1 |
| resultset_metadata | FULL |
| transaction_write_set_extraction | XXHASH64 |
+---------------------------------------+---------------------------------------------------------------+
16 rows in set, 1 warning (0.00 sec)
11.1.1.3. Setting and modifying system variables
For system variables, before the MySQL service starts, we can modify the my.cnf configuration file; or when starting, specify the startup parameters to modify.
After the service is started, the variable value can be modified through the set statement.
//修改全局变量
set global var_name = value;
set @@global.var_name = value;
//修改会话变量
set session var_name = value;
set @@session.var_name = value;
11.1.2. User variables
User variable refers to the variable defined by the user, which can assign a value to the user variable. Statements can be used to set 和 select
define assignments (no assignment is empty by default), and the select statement can also view the assigned value.
Variable scope: the session scope of the current connection (if the current connection is disconnected, the previously defined variables will not be accessible).
Define the form of user variables: start with '@', such as: "@var_name", so as to distinguish user variables and column names in the table. You can use '=',':='
the operator assignment. If you use the select statement, you must use ':='
the operator assignment
grammar:
set @var_name = value1 [ , @var_name = value2];
set @var_name := value1 [ , @var_name := value2];
set statement
mysql> set @test=123;
Query OK, 0 rows affected (0.00 sec)
mysql> select @test;
+-------+
| @test |
+-------+
| 123 |
+-------+
1 row in set (0.00 sec)
mysql> set @var1=1,@var2=2;
Query OK, 0 rows affected (0.00 sec)
mysql> select @var1,@var2;
+-------+-------+
| @var1 | @var2 |
+-------+-------+
| 1 | 2 |
+-------+-------+
1 row in set (0.00 sec)
select statement
mysql> select @var:=1,@var:=2;
+---------+---------+
| @var:=1 | @var:=2 |
+---------+---------+
| 1 | 2 |
+---------+---------+
1 row in set, 2 warnings (0.00 sec)
mysql> select @var,@var;
+------+------+
| @var | @var |
+------+------+
| 2 | 2 |
+------+------+
1 row in set (0.00 sec)
11.2. SQL system functions
11.2.1, Condition judgment function
if function
Syntax: if(expr1,expr2,expr3)
If the result of the expression is true (Boolean type), then return the value of expr2, otherwise return the value of expr3.
case structure
case case_expr
when when_value then statement_list
[ when when_value then statement_list ]...
end case
case_expr: Conditional judgment expression, which determines which when is executed. when_value: Indicates the possible value of the expression. If a when_value value is the same as the result of the case_expr expression value, the statement_list statement after the corresponding then keyword will be executed.
11.2.2. Mathematical functions
A commonly used function. Mainly used to process numbers, including
mathematical functions such as integers and floating point numbers
11.2.3. String functions
String functions are very commonly used functions. Processing for data type data.
string functions
11.2.4. Date function
11.2.5. Aggregate functions
Generally acts on the specified field.
aggregate function
11.3, custom function
If, case, loop, repeat, while, and for statements can be used in functions, please understand this part by yourself.
11.3.1. Create function
grammar:
create function func_name(func_parameter)
returns type
body
create function: keyword to create a function
func_name: function name
func_parameter: function parameter list, in the form of (param_nae type), such as: (num1 int, num2 int)
type: function return value type, such as: int, char(50) wait.
The general format of the body is as follows:
begin
retrun(select 查询语句);
end
delimiter delimiter: MySQL's default delimiter is a semicolon ';'. Using the delimiter statement, you can modify the default delimiter
example:
Create a function that queries the age of a reader.
delimiter $
create function func_reader_age2(name char(50))
returns int
begin
return(select year(curdate())-year(reader_birthday) from t_reader where reader_name=name);
end $
delimiter ;
select func_reader_age2("肖华");
11.3.2. Delete function
drop function function_name;
12. Trigger
A trigger is a stored procedure that executes automatically in response to a specific event. (Specific events: additions, deletions, and modifications to database tables)
triggers can be defined to be executed automatically before or after INSERT, UPDATE, and DELETE statements change the data table.
12.1, create a trigger
grammar:CREATE TRIGGER trigger_name trigger_time trigger_event ON table_name FOR EACH ROW [trigger_order] trigger_body
Detailed parameter explanation:
trigger_time: The execution time of the trigger: AFTER (after) | BEFORE (before)
trigger_event: The event triggered by the trigger: DELETE | UPDATE | INSERT
FOR EACH ROW: Indicates that the operation on any record that meets the trigger event will trigger the trigger
table_name: the name of the table element trigger event operation table
trigger_body: the SQL statement to create the trigger
(1) Create an Insert trigger. After inserting a record into t_student, insert the table name t_student and the insertion time into the t_log table.
CREATE TABLE t_log
(logno int AUTO_INCREMENT primary key,
tname varchar(20),
logtime datetime);
SELECT * FROM t_log;
create trigger tr_insert after insert on t_student for each row
insert into t_log (tname,logtime) VALUES('t_student',now());
insert into t_student(stu_id) values("0123456789");
select * from t_student;
select * from t_log;
(2) Create an insert trigger for the t_score1 table. When a piece of data is inserted into the t_score1 table, a record corresponding to stu_id is automatically added in t_student1, and a record corresponding to course_id is automatically added in t_course1e.
create table t_score1 like t_score;
insert into t_score1 select * from t_score;
//创建触发器
create trigger t_insert3 after insert on t_score1 for each row
begin
insert into t_student1(stu_id) VALUES("1123456789") ;
insert into t_course1(course_id) VALUES("12345678") ;
end
//验证
insert into t_score1(score_id,stu_id,course_id) values(1018,1631607101,16610001);
select * from t_student1 where stu_id = "1123456789";
select * from t_course1 where course_id = "12345678";
12.2, view the trigger
show triggers;
12.3. Delete trigger
drop trigger trigger_name;
12.4 Application of NEW and OLD
Two temporary tables, NEW and OLD, are defined in MySQL to save the table before and after the trigger modification for easy reference.
12.4.1. Flowchart
12.4.2. Case
(1) When modifying the birthday of a student in the table t_student1, insert the birthday before modification and the birthday after modification into another table t_backup (need to be created).
//创建触发器
create trigger t_updata1 after update on t_student1 for each row
begin
insert into t_backup(old_birthday,new_birthday) values(old.stu_birthday,new.stu_birthday);
end
//测试
update t_student1 set stu_birthday="1999-12-12" where stu_name="王伟";
(2) When deleting a record in the t_major1 table, insert the deleted record into another table (need to create a new table).
//创建触发器
create trigger t_delete1 after delete on t_major1 for each row
begin
insert into t_major_back values(old.major_id,old.major_name);
end
//测试
delete from t_major1 where major_name="计算机应用技术";
13. Affairs
grammar:
START TRANSACTION | BEGIN
DML语句
COMMIT 或 ROLLBACK
START TRANSACTION, BEGIN: can start a new transaction
DML statement: insert, delete, update
COMMIT, ROLLBACK: define commit, rollback transaction
13.1. Introduction
A transaction is a complete business logic and a unit of work. like:
Assuming a transfer, transfer 10,000 from account A to account B.
- Subtract 10000 from the money in account A (update statement)
Add 10000 to the money in account B (update statement)This is a complete business logic. The two updata statement requirements must both succeed or both fail .
Only DML statements will have transactions, and other statements have nothing to do with transactions! ! !
For insert, delete, and update,
only the above three statements are related to the transaction, and nothing else is related.
Therefore, a transaction is a batch of DML statements that succeed or fail at the same time
13.2, commit, rollback transaction
Commit the transaction: commit; statement, which represents the end of the transaction.
Rollback transaction: rollback; statement (rollback can only be rolled back to the last commit point forever!)
13.3, transaction includes 4 characteristics
A (atomic):
Explain that a transaction is the smallest unit of work. Indivisible.
C (Consistency):
All transactions require that in the same transaction, all operations must succeed or fail at the same time to ensure data consistency.
I (isolation) key points:
There is a certain isolation between A transaction and B transaction.
There is a wall between classroom A and classroom B, and this wall is isolation.
When transaction A operates a table, another transaction B also operates this table? ? ?
D (persistence):
A guarantee that a transaction will eventually close. Transaction submission is equivalent to saving data that has not been saved to the hard disk to the hard disk!
13.4. Case
Add 10 points to the C language score of the student whose student ID is "1631607101". If the score after adding 10 points is found to be greater than 100 points, execute the rollback operation of the transaction, otherwise submit the transaction.
mysql> select * from t_score1;
+----------+------------+-----------+-------+
| score_id | stu_id | course_id | grade |
+----------+------------+-----------+-------+
| 1001 | 1631607101 | 16610001 | 92 |
| 1002 | 1631607101 | 16610002 | 75 |
| 1003 | 1631607101 | 16610003 | 88 |
| 1004 | 1631607102 | 16610004 | 100 |
| 1005 | 1631607102 | 16610005 | 99 |
| 1006 | 1631611104 | 16610003 | 76 |
| 1007 | 1631611104 | 16610004 | 107 |
| 1008 | 1631611104 | 16610005 | 97 |
| 1009 | 1631611104 | 16610006 | 90 |
| 1010 | 1731613106 | 16610009 | 75 |
| 1011 | 1731613107 | 16610009 | 97 |
| 1012 | 1631601101 | 16610002 | 86 |
| 1013 | 1631601102 | 16610003 | 85 |
| 1014 | 1631601103 | 16610004 | 90 |
| 1015 | 1631601104 | 16610005 | 80 |
| 1016 | 1631601105 | 16610006 | 79 |
| 1017 | 1631601105 | 16610007 | 98 |
| 1018 | 1631607101 | 16610001 | NULL |
+----------+------------+-----------+-------+
18 rows in set (0.00 sec)
mysql> begin;
mysql> update t_score1 set grade=grade+10 where stu_id="1631607101";
mysql> select * from t_score1 where stu_id="1631607101" and grade < 100;
+----------+------------+-----------+-------+
| score_id | stu_id | course_id | grade |
+----------+------------+-----------+-------+
| 1002 | 1631607101 | 16610002 | 85 |
| 1003 | 1631607101 | 16610003 | 98 |
+----------+------------+-----------+-------+
--回滚后,数据就没有改变
mysql> rollback; --如果这里换成commit; 代表事务结束。
mysql> select * from t_score1 where stu_id="1631607101" and grade < 100;
+----------+------------+-----------+-------+
| score_id | stu_id | course_id | grade |
+----------+------------+-----------+-------+
| 1001 | 1631607101 | 16610001 | 92 |
| 1002 | 1631607101 | 16610002 | 75 |
| 1003 | 1631607101 | 16610003 | 88 |
+----------+------------+-----------+-------+
3 rows in set (0.00 sec)
--执行commit;后,就无法回到commit之前,代表事务结束。
mysql> commit;
14. User management and rights management
语法:CREATE USER user_name [IDENTIFIED BY [PASSWORD] “user_password”]
user_name: The created account name, a complete account consists of the user name and the host, in the form of
'user_name'@'localhost'
.
14.1. User Management
14.1.1. Create user
1. Default all hosts
create user test_1 identified by '123456';
2. Specify the user's host as localhost
create user test1@localhost identified by '123456';
14.1.2. Modify user password
14.1.3. Delete user
drop user user_name;
14.2. Authority Management
14.2.1. Authorization granted
GRANT priv_type[(column_list)] ON database.table TO user [IDENTIFIED BY [PASSWORD] 'password'] [,user IDENTIFIED BY [PASSWORD] 'password'] ... [WITH with-option['with-option']...]
priv_type: Authorization type (ALL means all permissions).
column_list: Specifies the column name, indicating that the permission acts on those columns, not specifying that it acts on the entire table.
database.table: Specifies the database and table.
user: username, a complete account is composed of username and host, in the form of'user_name'@'localhost'
.
IDENTIFIED BY: Specifies to set a password for the account, and the existing user does not need to specify a password.
password: Indicates the user's new password, and existing users can use no password.
WITH with-option['with-option']: Specifies authorization options.
1. Use the grant statement to create the user soft, the password is 123456, and grant select, insert, update permissions and delegation permissions (grant option) to all tables in all databases
grant select,insert,update on *.* to soft@localhost identified by '123456' with grant option;
2. Use the grant statement and grant select, insert, and update permissions to all tables in all databases
grant select,insert,update on *.* to soft;
14.2.1.1. View permission
grammar:GRANT priv_type[(column_list)] ON [object_type]{table_name | * | *.* | db_name.*} FROM user [,user]...
select * from user;
Ordinary users can also execute
show grants for ‘user'@'host';
14.2.2. Revoking permissions
revoke select,insert,update on *.* from soft@localhost;
15. Backup and restore database
15.1. Backup
grammar:
E:\db_backup>mysqldump
Usage: mysqldump [OPTIONS] database [tables]
OR mysqldump [OPTIONS] --databases [OPTIONS] DB1 [DB2 DB3...]
OR mysqldump [OPTIONS] --all-databases [OPTIONS]
For more options, use mysqldump --help
backup a database
MYSQLDUMP -u user_name -p db_name table_name1 table_name2... > backup_name.sql
user_name: User name
db_name: select the database for backup
table_name: select the table in the backup database
backup_name: the name of the generated backup file
backup multiple databases
MYSQLDUMP -u user_name -p --databases db_name1 db_name2... > backup_name.sql
backup all databases
MYSQLDUMP -u user_name -p --all-databases > backup_name.sql
15.2. Recovery
MYSQL -u user_name -p [db_name] < backup_name.sql
db_name: Used to specify the name of the database. When specifying a database, restore the tables under the database. When not specified, it means to restore all the data in the backup file.
16. Log
Four types of MySQL logs : error log, query log, slow query log, and binary log.
The files corresponding to the four types of logs are stored in the data directory of the mysql data directory. You can useshow variables
the command to view
the error log. The default is enabled, and the other three logs are defaulted to Open.
16.1. Error log
The error log records the error information when the MySQL service starts and stops and runs, such as: the syntax error of the running sql statement.
Error logging is enabled by default and cannot be disabled.
Check if "Error Log" is enabled
--使用show variables命令后可以看到日志文件存放位置:D:\APP\Pro_Software\MYSQL\data\
show variables like "%log_erro%";
+----------------------------+----------------------------------------------------+
| Variable_name | Value |
+----------------------------+----------------------------------------------------+
| binlog_error_action | ABORT_SERVER |
| log_error | D:\APP\Pro_Software\MYSQL\data\DESKTOP-T92IEER.err |
| log_error_services | log_filter_internal; log_sink_internal |
| log_error_suppression_list | |
| log_error_verbosity | 2 |
+----------------------------+----------------------------------------------------+
5 rows in set, 1 warning (0.00 sec)
16.2. Query log
The query log records the start and stop information of the MySQL server, client connection information, and SQL statements for adding, deleting, checking and modifying data records .
The query log is turned off by default. Since the query log will record all user operations, if the query log is enabled, it will take up more disk space. It is recommended to define the query log to save disk space.
Check if "Query Log" is enabled
--使用show variables命令后可以看到日志文件存放位置:D:\APP\Pro_Software\MYSQL\data\
mysql> show variables like "%general%";
+------------------+----------------------------------------------------+
| Variable_name | Value |
+------------------+----------------------------------------------------+
| general_log | OFF |
| general_log_file | D:\APP\Pro_Software\MYSQL\data\DESKTOP-T92IEER.log |
+------------------+----------------------------------------------------+
2 rows in set, 1 warning (0.00 sec)
--开启
mysql> set global general_log = ON;
Query OK, 0 rows affected (0.00 sec)
--关闭
mysql> set global general_log = OFF;
Query OK, 0 rows affected (0.00 sec)
16.3. Slow query log
Slow logging records various operations that take longer than a specified time to execute .
By analyzing the slow query log, you can effectively locate the performance bottleneck of each MySQL command execution.
Check if "Slow Query Log" is enabled
--使用show variables命令后可以看到日志文件存放位置:D:\APP\Pro_Software\MYSQL\data\
mysql> show variables like "%slow%";
+-----------------------------+---------------------------------------------------------+
| Variable_name | Value |
+-----------------------------+---------------------------------------------------------+
| log_slow_admin_statements | OFF |
| log_slow_extra | OFF |
| log_slow_replica_statements | OFF |
| log_slow_slave_statements | OFF |
| slow_launch_time | 2 |
| slow_query_log | OFF |
| slow_query_log_file | D:\APP\Pro_Software\MYSQL\data\DESKTOP-T92IEER-slow.log |
+-----------------------------+---------------------------------------------------------+
7 rows in set, 1 warning (0.01 sec)
--开启
mysql> set global slow_query_log=on;
Query OK, 0 rows affected (0.00 sec)
--关闭
mysql> set global slow_query_log = off;
Query OK, 0 rows affected (0.00 sec)
--测试
mysql> select sleep(10);
+-----------+
| sleep(10) |
+-----------+
| 0 |
+-----------+
1 row in set (10.01 sec)
16.4, binary log
The two-level log records various operations of the database in binary form other than queries, also called a change log. It is mainly used to record MySQL statements that modify data or may cause data changes, and record the statement occurrence time, execution time, and operation data .
Check if "binary log" is enabled
--使用show variables命令后可以看到日志文件存放位置:D:\APP\Pro_Software\MYSQL\data\
mysql> show variables like "%log_bin%";
+---------------------------------+---------------------------------------------+
| Variable_name | Value |
+---------------------------------+---------------------------------------------+
| log_bin | ON |
| log_bin_basename | D:\APP\Pro_Software\MYSQL\data\binlog |
| log_bin_index | D:\APP\Pro_Software\MYSQL\data\binlog.index |
| log_bin_trust_function_creators | OFF |
| log_bin_use_v1_row_events | OFF |
| sql_log_bin | ON |
+---------------------------------+---------------------------------------------+
6 rows in set, 1 warning (0.00 sec)
--查询binlog文件名
mysql> show master status;
+---------------+----------+--------------+------------------+-------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+---------------+----------+--------------+------------------+-------------------+
| binlog.000119 | 57106 | | | |
+---------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)
Summarize
I am Qiuyilin, welcome everyone to join the cloud community with one click and three links
See you next time (⊙o⊙)! ! !