简体   繁体   中英

Lock at MyISAM Table (MySQL) and PHP

The Table in MySQL is MyISAM.

Now i want to select many data.

$res = $db->query("SELECT ...");
// -- Break 1
while($row = $res->fetch_assoc()) {
 //working with the row;
}
// -- Break 2

When does the lock on the table ends? On Break 1 or Break 2?

@bauer as far as i have understood your question. The answer near to me is whenever you are working with while loop and you have a resource object or variable on which you iterate, its only done once on the page, because once the iteration is complete the object or the respective variable would get free and contains null, so in order to run bundle of while loops you need to define different obj each irrespective to your result set.

// -- Break 1

The data loads during the process before this line. Table is released.

Further data manipulation from this point is in the PHP application and no longer requires data from the DB.

As for the earlier comment that there is no data lock, that depends on your point of view. If your query returns two records quickly, it would appear there is no lock (technically incorrect, but easily mistaken). But if your query is complex and your result set huge, which requires some serious time to return results (on the order of 45 seconds, for instance) it will become painfully obvious that there is indeed a table lock in MyISAM. A simple "show processlist" during a 45 second return clearly shows locked tables. (Waiting for table level lock is kind of a dead giveaway). Happens every day on larger Vicidial installations.

Indexing the table can often reduce the lock time. Setting "limit 50" (some number to limit the resulting data set) can reduce the lock time if that's a viable option for the query as well.

Also do note that the locking has some methods of bypass depending on the query trying to "play through". Selects vs inserts vs updates can often bypas one another (that's where the studying of the locking mechanisms can come in handy). And testing is a good idea to be sure you understand it. Never fear creating a table with 30 million records in it and running a huge query to see what locks and what does not between select/insert/update while one of them is huge and another is tiny and trying to "play through" while the big one is running. Results can surprise you even if you think you "got it". And then watch for the ability to explicitly state that a query is less important and what happens when the subsequent queries rotate their types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM