MYSQL nested query running very slow?

ぃ、小莉子 提交于 2021-02-09 18:58:09

问题


The following query is constantly timing out, is there a less overhead way to achieve the same function ?

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

What I'm doing is unallocating invoices from a transaction, there can be up to 30+ records returned but it stops the database dead everytime I try to run it


回答1:


USE JOIN instead of subquery it will improve the performance.

Create index on Invoice_number column in both table if you haven't created.

Try this:

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



回答2:


I'd try 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
)



回答3:


As of MySQL 5.5, Subquery Selects (another full select statement inside the query) cannot be optimized. This is probably why your query is so slow. Refactor you query to get rid of the inner select statement.

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

An interesting sidenote... But MariaDB (a branch of MySQL by the original creator) has implemented Subquery select optimization.




回答4:


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


来源:https://stackoverflow.com/questions/14383100/mysql-nested-query-running-very-slow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!