0

我发现以下查询导致了一些瓶颈(执行时间超过 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部分,对吗?有没有办法改进它?

4

3 回答 3

2

这应该快一点:

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 列创建索引(如果您还没有索引)。

于 2012-10-05T08:34:24.443 回答
2

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

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
于 2012-10-05T08:41:21.720 回答
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)
于 2012-10-05T08:46:57.400 回答