我正在处理导致一些死锁的查询,我相信因为它试图从同一个表中进行SELECT更新。无论如何,这是一种非常笨拙的方式,我想找到一个更好的方法。
这里一个明显的解决方案是将SELECT拉出到一个单独的查询中,但是我希望你们中的一个SQL忍者有一个更优雅的解决方案的建议,可以在单个查询中完成开销要少得多。
SET @update_id := 0;
UPDATE msgstream
SET retryCount = retryCount + 1,
retryTime = TIMESTAMPADD(SECOND,?,NOW(3)),
messageid = (SELECT @update_id := messageid)
WHERE receiver = ?
AND isDelivered = 0
AND retryCount < 10
AND retryTime < NOW(3)
AND (
SELECT m.counter
FROM (
SELECT COUNT(messageid) AS counter
FROM msgstream
WHERE receiver = ?
AND isDelivered = 0
AND retryCount < 10
AND retryTime > NOW(3)
) AS m
) = 0
ORDER BY messageid LIMIT 1;