MYSQL嵌套查询运行速度很慢?

时间:2013-01-17 16:02:53

标签: mysql join sql-update subquery

以下查询不断超时,是否有更少的开销方式来实现相同的功能?

UPDATE Invoices SET ispaid = 0 
WHERE Invoice_number IN (SELECT invoice_number
    FROM payment_allocation
    WHERE transactionID=305)

我正在做的是从一个事务中取消分配发票,最多可以返回30多条记录但是每当我尝试运行它时它就会停止数据库死亡

4 个答案:

答案 0 :(得分:5)

使用加入而不是子查询,它将提高性能。

如果您尚未创建,请在两个表格中的 Invoice_number 列上创建索引。

试试这个:

UPDATE Invoices i 
INNER JOIN payment_allocation pa ON i.Invoice_number = pa.invoice_number 
SET i.ispaid = 0 
WHERE pa.transactionID = 305;

答案 1 :(得分:2)

我会尝试EXISTS

UPDATE Invoices a set ispaid=0 
WHERE EXISTS 
(
 SELECT NULL FROM payment_allocation b 
 WHERE b.Invoice_number =a.Invoice_number AND b.transactionID=305
)

答案 2 :(得分:1)

从MySQL 5.5开始,无法优化子查询选择(查询中的另一个完整选择语句)。这可能是您的查询速度太慢的原因。重构您查询以摆脱内部select语句。

 UPDATE Invoices, payment_allocation
  SET ispaid=0 
  WHERE payment_allocation.transactionID=305 AND       
        Invoices.Invoice_number = payment_allocation.invoice_number 

一个有趣的旁注......但MariaDB(由原始创建者创建的MySQL分支)已经实现了Subquery选择优化。

答案 3 :(得分:0)

UPDATE invoices i
  JOIN payment_allocation pa
    ON pa.invoice_number = i.invoice_number
   SET i.ispaid=0 
 WHERE pa.transactionID = 305;