Home > Database > Mysql Tutorial > How to Run SELECT Statements in MySQL Without Locking?

How to Run SELECT Statements in MySQL Without Locking?

DDD
Release: 2024-12-14 18:33:12
Original
408 people have browsed it

How to Run SELECT Statements in MySQL Without Locking?

How to Execute SELECT Statements Without Causing Locks in MySQL

In MySQL, executing SELECT statements can sometimes trigger locks, particularly when the underlying table is undergoing concurrent modifications. This can be problematic, especially on slave databases that rely on binlogging.

One potential solution, suggested in the provided article, is utilizing the "NOLOCK" modifier. However, MySQL does not support an equivalent keyword. Instead, you can achieve the same effect by adjusting the transaction isolation level.

Solution: Read Uncommitted Transaction Isolation Level

To avoid locks while executing SELECT statements, you can set the transaction isolation level to "READ UNCOMMITTED." This allows uncommitted transactions to be visible, preventing locks from occurring. Here's how to do it:

SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SELECT COUNT(online.account_id) cnt from online;
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
Copy after login

Slave Database Compatibility

When using the READ UNCOMMITTED isolation level on a slave database, you may encounter the error: "Binary logging not possible...Transaction level 'READ-UNCOMMITTED' in InnoDB is not safe for binlog mode 'STATEMENT.'" To resolve this, you can modify the my.cnf file on the master database to enable the "READ UNCOMMITTED" transaction isolation level for binlogging.

Alternative Solution

Alternatively, you can use the following technique instead of setting the isolation level:

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SELECT COUNT(online.account_id) cnt from online;
COMMIT;
Copy after login

This forces the query to read uncommitted data and then immediately commit the transaction, preventing any potential locks or conflicts.

Note that using the READ UNCOMMITTED isolation level allows access to uncommitted data, which may lead to data inconsistencies. It's important to consider the potential risks and use it cautiously when necessary.

The above is the detailed content of How to Run SELECT Statements in MySQL Without Locking?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template