0

谁能帮我优化这个查询。我无法执行它,因为 phpMyAdmin 连接超时并且我无权更改超时参数。

这是一个查询:

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`
)
4

1 回答 1

0

除了确保您的表被正确索引之外,您还可以将IN子查询替换为INNER JOIN,并且您的NOT IN子查询 WITH LEFT JOIN/IS NULL,这应该会提高性能:

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`
于 2013-04-25T10:45:44.693 回答