Mysql series article home page
===============
1 Prepare data
1.1 Create a table
1.1.1 Create the Employee table
DROP TABLE IF EXISTS employee; CREATE TABLE IF NOT EXISTS employee ( id INT PRIMARY KEY auto_increment, name VARCHAR(40), dept_id INT )engine myisam;
1.1.2 Create the Department table
DROP TABLE IF EXISTS department; CREATE TABLE IF NOT EXISTS department ( id INT PRIMARY KEY auto_increment, name VARCHAR(40) )engine myisam;
1.1.3 Note: The storage engines of the above two tables are MyISam
1.2 Insert data
INSERT INTO employee(name, dept_id) VALUES('Alice', 1); INSERT INTO employee(name, dept_id) VALUES('Bob', 1);
INSERT INTO department(name) VALUES('RD');
2 test
2.1 Add a read lock to the Employee table
LOCK TABLE employee READ;
2.2 Query the Employee table
2.2.1 Current session (terminal, command line window)
Note: The current session refers to the session (window, command line) that executed the LOCK TABLE employee READ statement above; in my case, the white background .
SELECT * FROM employee;
2.2.2 Other sessions (terminal, command line window)
Note: Open a new session window; in my case, a black background .
2.2.3 Conclusion
It can be seen that after adding a read lock, both the current session and other sessions can perform read operations, that is, read locks are shared for read operations .
2.3 Update the Employee table
2.3.1 Current session
UPDATE employee SET name = 'Alice02' WHERE id = 1;
2.3.2 Other sessions
Result: suspended, blocked (above)
Next, execute the UNLOCK TABLES command in the 'current session' to unlock the lock (above)
After unlocking, the update statement in 'other session' is executed immediately; as you can see, it takes 1 min 5.11 sec (above)
2.3.3 Conclusion
For update operations:
- The current session cannot be updated (understanding: adding a read lock, of course, cannot perform write (update) operations)
- Other sessions must wait until the current session is unlocked before updating, otherwise it will hang (after all, the 'current session' has a lock, and 'other sessions' must not be able to write)
2.4 Reading other tables
2.4.0 Preparation
Hint: The 'current session' needs to lock the Employee table again (because UNLOCK TABLES was executed above)
LOCK TABLE employee READ;
2.4.1 Current session
SELECT * FROM department;
2.4.2 Other sessions
2.4.3 Conclusion
For read operations from other tables:
- The current session cannot be read (the Department table is not locked and cannot be read)
- Other sessions can read normally
3 Conclusion
Read lock, for the current session (Owner), the locked table can be read, but it cannot be updated, nor can it read other tables;
For other sessions (Other), the locked table can be read, the update will be blocked, and other tables can be read normally;
Read locks are shared for read operations;