Avoiding 'Deadlock Found When Trying to Get Lock' in MySQL
Issue:
A developer encounters intermittent 'Deadlock found when trying to get lock; try restarting transaction' errors when running INSERTs into an InnoDB table that tracks online user activities. The table is updated on page refresh and cleared every 15 minutes by a cron job.
Queries in Question:
Solution:
To resolve deadlocks, it's crucial to ensure that transactions lock keys in a consistent order. Here are the recommended steps:
Order Keys in Queries:
Sort Delete Statements:
DELETE FROM onlineusers WHERE id IN ( SELECT id FROM onlineusers WHERE datetime <= now() - INTERVAL 900 SECOND ORDER BY id ) u;
Retry Mechanism:
The above is the detailed content of How Can I Prevent 'Deadlock Found When Trying to Get Lock' Errors in My MySQL Online User Tracking System?. For more information, please follow other related articles on the PHP Chinese website!