开发者

Optimising (My)SQL Query

I usually use ORM instead of SQL and I am slightly out of touch on the different JOINs...

SELECT `order_invoice`.*
     , `client`.*
     , `order_product`.*
     , SUM(product.cost) as net 
  FROM `order_invoice` 
  LEFT JOIN `client` 
    ON order_invoice.client_id = client.client_id 
  LEFT JOIN `order_product` 
    ON order_invoice.invoice_id = order_product.invoice_id 
  LEFT JOIN `product` 
    ON order_product.product_id = product.product_id 
 WHERE (order_invoice.date_created >= '2009-01-01') 
   AND (order_invoice.date_created <= '2009-02-01') 
 GROUP BY `order_invoice`.`invoice_id`

The tables/ columns are logically names... it's an shop type application... the query works... it's just very very slow...

I use the Zend Framework and would usually use Zend_Db_Table_Row::find(Parent|Dependent)Row(set)('TableClass') but I have to make lots of joins and I thought it'll 开发者_Python百科improve performance by doing it all in one query instead of hundreds...

Can I improve the above query by using more appropriate JOINs or a different implementation? Many thanks.


The query is wrong, the GROUP BY is wrong. All columns in the SELECT-part that are not in an aggregate function, have to be in the GROUP BY. You mention only one column.

Change the SQL Mode, set it to ONLY_FULL_GROUP_BY.

When this is done and you have a correct query, use EXPLAIN to find out how the query is executed and what indexes are used. Then start optimizing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜