tags:

views:

55

answers:

2

I know the best way would be not to have any sql inside other sql, specially a complicated one, and would be better to use the analysis after the query, but because the way the system is build I would preffer to do it only on one query

Here is the query in question ("is a really cool query")

SELECT DISTINCT
  o.orders_id,
  o.faltantes,
  o.customers_name,
  o.payment_method,
  o.date_purchased,
  o.last_modified,
  o.currency,
  o.currency_value,
  ot.text          AS order_total,
  st.stores_name
FROM (orders o
   LEFT JOIN orders_total ot
     ON (o.orders_id = ot.orders_id),
   stores st,
   orders_status s)
  INNER JOIN orders_products op
    ON (o.orders_id = op.orders_id)
WHERE o.orders_status != 19
    AND ot.class = 'ot_total'
    AND (ot.value > (SELECT
                       SUM(pc.monto)        +SUM(p.monto)
                     FROM pagos_clientes pc,
                       pagos p
                     WHERE p.id_pago = pc.id_pago
                         AND pc.id_oferta = o.orders_id)
          OR (SELECT
                SUM(pc.monto)        +SUM(p.monto)
              FROM pagos_clientes pc,
                pagos p
              WHERE p.id_pago = pc.id_pago
                  AND pc.id_oferta = o.orders_id)IS NULL)
    AND payment_method != 'Cambio por faltantes'
    AND o.orders_stores_id = '3'
    AND o.orders_stores_id = st.stores_id
    AND ((o.orders_stores_id IN(1,3))
          OR (op.products_distributors_id = '0'))
GROUP BY o.orders_id
ORDER BY o.orders_id DESC

Thanks to anybody that can solve this question :D (currently it takes arround 2 minutes Real Time)

+2  A: 

Usually it's a big improvement to move a subquery into FROM. http://dev.mysql.com/doc/refman/5.1/en/rewriting-subqueries.html

Don't use comma joins, mix of proper JOINs and comma joins often breaks.
And I see that orders_status s table hasn't relation to any other table. Adding a proper relation should increase performance many times.

Use EXPLAIN to analyze query performance and find a places for optimizations.

Naktibalda
Thank you very much, it was the orders_status, it remains from an old query,personally I hate joins, and right now I'm hating Germans because they beat Argentina at WC (2006, 2010 And of course and specially 1990) but at this moment is because they built the oscommerce :DThank ou again Naktibalda :DAny way I know that I have to optimize the code anyway :P
Saikios
A: 

The output of your EXPLAIN shows that there are not enough indexes for your query to be able to run without performing full table scans. The worst offender is the orders_products table which does not have a suitable index on the orders_id column.

You should check that each column used in your JOIN conditions has an index. This alone will help a great deal.

Mike
Thanks Mike I will check that :)
Saikios