运行查询时MySQL挂起。我怎样才能提高效率呢?

时间:2010-06-21 14:45:00

标签: sql mysql query-optimization

5 个答案:

答案 0 :(得分:1)

使用explain来分析查询执行计划: http://dev.mysql.com/doc/refman/5.1/en/using-explain.htmlhttp://dev.mysql.com/doc/refman/5.1/en/explain.html

通常,WHERE中的子查询非常慢,请尝试将它们重写为JOIN。

答案 1 :(得分:0)

它是WHERE子句中的子查询。 Naktibala在那里击中钉头......

您还可以尝试为子查询获取的数据创建一些临时表。基本上,将您需要的数据放入临时表,然后将这些表正常连接到基本查询。一旦完成,您就可以简化/调整。

答案 2 :(得分:0)

由于您已按订单ID加入商品和交易, 我认为您可以删除子查询条件,并将检查移至HAVING。

尝试运行此查询:

SELECT SQL_CALC_FOUND_ROWS i.order_id, o.*, acct.*, SUM(items.item_qty) AS order_qty
FROM items AS i
INNER JOIN orders AS o ON o.order_id = i.order_id
INNER JOIN transactions AS t ON t.order_id = o.order_id
INNER JOIN accounts AS acct ON o.acct_id = acct.acct_id
INNER JOIN ship_to AS st ON o.ship_id = st.ship_id
WHERE o.order_status=7 AND o.order_date > '2009-05-01 00:00:00'
AND acct.is_wholesale=1
GROUP BY o.order_id
HAVING ( SUM(items.item_price) * SUM(items.item_qty) + o.order_ship_amount - SUM(transactions.trans_amount) ) != 0
ORDER BY o.order_date
LIMIT $offset, $limit

答案 3 :(得分:0)

看看这是否更简单地描述了您的查询 (而且效率不高。)

SELECT   
    o.order_id,  
    o.order_ship_amount,  
    SUM(i.item_qty * i.item_price) AS item_amount,  
    SUM(trans_amount) AS trans_amount,  
    ... etc.
FROM  
    orders AS o  
INNER JOIN accounts AS acct ON o.acct_id = acct.acct_id  
INNER JOIN ship_to AS st ON o.ship_id = st.ship_id  
INNER JOIN items AS i ON o.order_id = i.order_id  
LEFT JOIN transactions AS t ON t.order_id = o.order_id  
    AND trans_pending = 0  
WHERE   
    o.order_status = 7   
    AND o.order_date > '2009-05-01 00:00:00'  
    AND acct.is_wholesale = 1   
GROUP BY o.order_id  
HAVING item_amount + order_ship_amount - trans_amount != 0  
ORDER BY o.order_date  

确保您可以阅读并理解它 - 我还没有测试过它。

答案 4 :(得分:0)

SELECT   
    o.order_id,  
    o.order_ship_amount,  
    SUM(i.item_qty * i.item_price) AS item_amount,  
    (   SELECT SUM(trans_amount) FROM transactions
        WHERE order_id = o.order_id AND trans_pending = 0
    ) AS trans_amount,
    ... etc.
FROM  
    orders AS o  
INNER JOIN accounts AS acct ON o.acct_id = acct.acct_id  
INNER JOIN ship_to AS st ON o.ship_id = st.ship_id  
INNER JOIN items AS i ON o.order_id = i.order_id  
WHERE   
    o.order_status = 7   
    AND o.order_date > '2009-05-01 00:00:00'  
    AND acct.is_wholesale = 1   
GROUP BY o.order_id  
HAVING item_amount + order_ship_amount - trans_amount != 0  
ORDER BY o.order_date