我发现以下查询引起了一些瓶颈(执行时间超过40秒!)

DELETE FROM doctors
WHERE (SELECT COUNT(loc_id)
       FROM locations
       WHERE locations.loc_doctor = doctors.doc_id) = 0 AND
       doctors.doc_user = $myVar


我想问题出在(SELECT COUNT(loc_id) FROM locations WHERE locations.loc_doctor = doctors.doc_id) = 0部分,对吗?
有办法改善吗?

最佳答案

这应该快一点:

DELETE FROM doctors WHERE doctors.doc_user = $myVar AND NOT EXISTS (SELECT 1 FROM locations WHERE locations.loc_doctor = doctors.doc_id LIMIT 1)


由于您计数为0实际上是NOT EXISTS检查。您还应该考虑为locations.loc_doctor列创建索引(如果还没有索引的话)。

关于mysql - 使用COUNT时改善MySQL删除查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12742406/

10-13 09:54