2013-04-25 47 views
0

任何人都可以幫助我優化此查詢。我無法執行它,因爲phpMyAdmin連接超時,我無法更改超時參數。優化MySQL查詢,因爲它會超時

下面是一個查詢:

INSERT INTO `goods` (`goods_id`, `price`, `name`) 
SELECT `sales_goods`.`goods_id`, `sales_goods`.`price`, `sales_goods`.`goods_id` 
FROM `sales_goods` 
WHERE `sales_goods`.`sales_goods_id` 
IN (
    SELECT MAX(`sales_goods`.`sales_goods_id`) 
    FROM `sales_goods` 
    WHERE `sales_goods`.`sales_goods_id` 
    IN (
     SELECT `sales_goods`.`sales_goods_id` FROM `sales_goods` 
     WHERE `sales_goods`.`goods_id` NOT IN (SELECT `goods`.`goods_id` FROM `goods`) 
    ) 
    GROUP BY `sales_goods`.`goods_id` 
) 
+1

避免IN子句它是性能殺手...我的意思是嘗試將查詢更改爲JOINS而不是嵌套INs – 2013-04-25 10:25:17

+2

即使在翻譯來自立陶宛語的查詢之後,它有點h想知道你想做什麼... – 2013-04-25 10:29:15

+0

我同意,我無法理解它 - 我想我知道..但是這個MAX?!? @ user2319233試圖解釋你的目標 – 2013-04-25 10:41:26

回答

0
從確保你的表

除了在屬性格式索引可以用INNER JOIN取代你IN子查詢,以及LEFT JOIN/IS NULLNOT IN子查詢,這應該提高性能:

INSERT INTO `goods` (`goods_id`, `price`, `name`) 
SELECT `sales_goods`.`goods_id`, 
     `sales_goods`.`price`, 
     `sales_goods`.`goods_id` 
FROM `sales_goods` 
     INNER JOIN 
     ( SELECT MAX(`sales_goods`.`sales_goods_id`) 
      FROM `sales_goods` 
        LEFT JOIN `goods` 
         ON `goods`.`goods_id` = `sales_goods`.`goods_id` 
      WHERE `goods`.`goods_id` IS NULL 
      GROUP BY `sales_goods`.`goods_id` 
     ) MaxSalesGoods 
      ON MaxSalesGoods.sales_goods_id = `sales_goods`.`sales_goods_id` 
+0

謝謝,它有幫助 – Ellis 2013-04-25 12:24:25