问题
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