Any way to select without causing locking in MySQL?

后端 未结 8 1565
执笔经年
执笔经年 2020-11-22 15:21

Query:

SELECT COUNT(online.account_id) cnt from online;

But online table is also modified by an event, so frequently I can see lock by runn

相关标签:
8条回答
  • 2020-11-22 15:23

    Use

    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED.

    Version 5.0 Docs are here.

    Version 5.1 Docs are here.

    0 讨论(0)
  • 2020-11-22 15:26

    Found an article titled "MYSQL WITH NOLOCK"

    https://web.archive.org/web/20100814144042/http://sqldba.org/articles/22-mysql-with-nolock.aspx

    in MS SQL Server you would do the following:

    SELECT * FROM TABLE_NAME WITH (nolock)
    

    and the MYSQL equivalent is

    SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;
    SELECT * FROM TABLE_NAME ;
    SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;
    

    EDIT

    Michael Mior suggested the following (from the comments)

    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;
    SELECT * FROM TABLE_NAME ;
    COMMIT ;
    
    0 讨论(0)
  • 2020-11-22 15:28

    If the table is InnoDB, see http://dev.mysql.com/doc/refman/5.1/en/innodb-consistent-read.html -- it uses consistent-read (no-locking mode) for SELECTs "that do not specify FOR UPDATE or LOCK IN SHARE MODE if the innodb_locks_unsafe_for_binlog option is set and the isolation level of the transaction is not set to SERIALIZABLE. Thus, no locks are set on rows read from the selected table".

    0 讨论(0)
  • 2020-11-22 15:34

    SELECTs do not normally do any locking that you care about on InnoDB tables. The default transaction isolation level means that selects don't lock stuff.

    Of course contention still happens.

    0 讨论(0)
  • 2020-11-22 15:35

    You may want to read this page of the MySQL manual. How a table gets locked is dependent on what type of table it is.

    MyISAM uses table locks to achieve a very high read speed, but if you have an UPDATE statement waiting, then future SELECTS will queue up behind the UPDATE.

    InnoDB tables use row-level locking, and you won't have the whole table lock up behind an UPDATE. There are other kind of locking issues associated with InnoDB, but you might find it fits your needs.

    0 讨论(0)
  • 2020-11-22 15:38

    From this reference:

    If you acquire a table lock explicitly with LOCK TABLES, you can request a READ LOCAL lock rather than a READ lock to enable other sessions to perform concurrent inserts while you have the table locked.

    0 讨论(0)
提交回复
热议问题