sql - 这会锁定数据库吗?

标签 sql mysql

insert into test.qvalues 
  select * from qcvalues.qvalues;

我想知道上面的行是否锁定了数据库 QCVALUES

最佳答案

对我来说,文档有点不清楚:

Internal Locking Methods建议,在某些情况下,可以在另一个 session 正在读取 MyISAM 表时插入:

The MyISAM storage engine supports concurrent inserts to reduce contention between readers and writers for a given table: If a MyISAM table has no free blocks in the middle of the data file, rows are always inserted at the end of the data file. In this case, you can freely mix concurrent INSERT and SELECT statements for a MyISAM table without locks. That is, you can insert rows into a MyISAM table at the same time other clients are reading from it. Holes can result from rows having been deleted from or updated in the middle of the table. If there are holes, concurrent inserts are disabled but are enabled again automatically when all holes have been filled with new data.

然而,Table Locking Issues显示了在 SELECT 完成之前表将被锁定的情况(这符合您的情况):

Table locking is also disadvantageous under the following scenario:

  • A session issues a SELECT that takes a long time to run.
  • Another session then issues an UPDATE on the same table. This session waits until the SELECT is finished.
  • Another session issues another SELECT statement on the same table. Because UPDATE has higher priority than SELECT, this SELECT waits for the UPDATE to finish, after waiting for the first SELECT to finish.

InnoDB 表实现行级锁,因此只会锁定正在读取的行,而不是整个表。

我没有仅仅依赖文档,而是尝试了一些测试:

  1. 创建两个具有相同结构的表:table_atable_b
  2. 用 500,000 行填充 table_a
  3. 使用 INSERT INTO ... SELECT 语句将数据从 table_a 复制到 table_b
  4. 在复制过程中,使用另一个 session 将新行插入到table_a
  5. 检查 table_b 是否包含新记录。

当两个表都在 MyISAM 中时,table_b 不包含复制后的新记录。当两个表都在 InnoDB 中时,table_b 确实包含复制后的新记录。我重复了 3 次,不出所料,每次的结果都一样。

所以,简而言之,如果你的表是MyISAM,它就会被锁定。如果是 InnoDB,则不会。当然,这个测试不考虑更新,但我希望结果会相似。

关于sql - 这会锁定数据库吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3312361/

相关文章:

c# - 另一个sql查询语句

php - 摆脱重复的行

sql - 对索引列进行全表扫描?

php - 如何通过在 php 中使用 javascript 选择从 SQL 填充的下拉列表来将 SQL 中的值检索到文本区域中

mysql - MySQL 子查询的结果不准确

php - 生成唯一的 8 个字符的十六进制字符串

php - 外键MySQL错误,带帖子

c# - C#如何计算sql表的行数?

mysql大表查询优化group by

MYSQL:在不递归运行查询的情况下计算值在结果中出现的次数