在使用COUNT时改进MySQL删除查询

在使用COUNT时改进MySQL删除查询,mysql,count,sql-delete,Mysql,Count,Sql Delete,我发现下面的查询造成了一些瓶颈,执行时间超过40秒 DELETE FROM doctors WHERE (SELECT COUNT(loc_id) FROM locations WHERE locations.loc_doctor = doctors.doc_id) = 0 AND doctors.doc_user = $myVar 我想问题在于从locations.loc\u doctor=doctors.doc\u id=0的位置选择COU

我发现下面的查询造成了一些瓶颈,执行时间超过40秒

DELETE FROM doctors 
WHERE (SELECT COUNT(loc_id) 
       FROM locations 
       WHERE locations.loc_doctor = doctors.doc_id) = 0 AND 
       doctors.doc_user = $myVar
我想问题在于从locations.loc\u doctor=doctors.doc\u id=0的位置选择COUNTloc\u id部分,对吗?
有没有改进的方法?

这应该快一点:

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的计数实际上是一个不存在的检查。你也应该考虑一个Loosix.LoopHub列的索引,如果你已经没有一个了。

这应该快一点:

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的计数实际上是一个不存在的检查。你也应该考虑一个Loosix.LoopHub列的索引,如果你已经没有一个了。

< P>我建议从外部连接删除:

DELETE doctors
FROM doctors LEFT JOIN locations
   ON locations.loc_doctor = doctors.doc_id
WHERE locations.loc_id IS NULL
AND doctors.doc_user = $myVar

我建议从外部连接中删除:

DELETE doctors
FROM doctors LEFT JOIN locations
   ON locations.loc_doctor = doctors.doc_id
WHERE locations.loc_id IS NULL
AND doctors.doc_user = $myVar
我想对@tpeczek答案增加限制

DELETE FROM doctors WHERE doctors.doc_user = $myVar AND NOT EXISTS (SELECT * FROM locations WHERE locations.loc_doctor = doctors.doc_id limit 1)
我想对@tpeczek答案增加限制

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

是的,没错,不需要检查0。它工作得非常快!:-谢谢,我不知道不存在选项!执行不存在搜索时隐式使用限制1。而且,这似乎也比不上提奥米奇的答案。查看此链接:是的,这是真的,不需要检查0。它工作得非常快!:-谢谢,我不知道不存在选项!执行不存在搜索时隐式使用限制1。而且,这似乎也比不上提奥米奇的答案。请参阅此链接:执行“不存在”搜索时隐式使用限制1。还有一篇关于比较NOT EXISTS与LEFT JOIN/IS NULL的文章。。。执行不存在搜索时隐式使用限制1。还有一篇关于比较NOT EXISTS与LEFT JOIN/IS NULL的文章@QuadroQ感谢您提供的文档链接,这让我信服了!你在这里提出的想法太棒了@QuadroQ感谢您提供的文档链接,这让我信服了!你在这里提出的想法太棒了!