Reputation: 11
I have trying to execute the following sql query with good response time, but when I add the ORDER BY statement the query doesn't return anything for more than 5 min.
SELECT *
FROM orders co
LEFT JOIN (SELECT * FROM prod_orders) AS pc
ON co.id_order = pc.id_order
LEFT JOIN (SELECT * FROM clients) AS cl
ON co.id_client = cl.id_client
LEFT JOIN (SELECT * FROM clients_address) AS ca
ON co.id_client = ca.id_client
LEFT JOIN (SELECT * FROM clienti_firme) AS cf
ON ca.id_client = cf.id_client
ORDER BY co.id_order
Upvotes: 0
Views: 355
Reputation: 1205
If the Order By is slowing it down try:
SELECT *
FROM (SELECT * FROM orders ORDER BY id_order) AS co
LEFT JOIN prod_orders AS pc
ON co.id_order = pc.id_order
LEFT JOIN clients AS cl
ON co.id_client = cl.id_client
LEFT JOIN clients_address AS ca
ON co.id_client = ca.id_client
LEFT JOIN clienti_firme AS cf
ON ca.id_client = cf.id_client
ORDER BY co.id_order
Maybe the execution plan of all of the derived tables is making it run SELECT * for each row of the first table (orders). Try this instead:
SELECT *
FROM orders co
LEFT JOIN prod_orders AS pc
ON co.id_order = pc.id_order
LEFT JOIN clients AS cl
ON co.id_client = cl.id_client
LEFT JOIN clients_address AS ca
ON co.id_client = ca.id_client
LEFT JOIN clienti_firme AS cf
ON ca.id_client = cf.id_client
ORDER BY co.id_order
Upvotes: 1
Reputation: 48139
The query provided by Sean is about as simple as it would get... That said, I would ensure you have the following indexes on all respective tables
prod_orders ( id_order )
clients ( id_client )
clients_address ( id_client )
clienti_firme (id_client)
and of course your
orders ( id_order )
The only ADDITIONAL thing I would since you mentioned MySQL. try adding the keyword "STRAIGHT_JOIN"... I don't think it would make a difference since all your tables are LEFT-JOINs, but you never know.
SELECT STRAIGHT_JOIN ... rest of query ...
The only other thing I can think of that may be killing it is some sort of Cartesian result of data. yes, an order should be associated with a single client, but if that client has multiple addresses (home, work, alternate office, etc and we don't know your table relationships), and again for clienti_firme (multiple records the client is associated with), you could be blowing through more than you expect.
If you have 100 orders for a single client, and that client has 3 addresses and is associated with 10 firms, you now have 100 * 3 * 10 records coming through where you may have originally expected only 100 (now getting 3000). Do that with all the orders, clients, etc and you see how it COULD become a problem.
Upvotes: 0