如何优化这个MySQL SQL查询?

时间:2015-01-18 15:39:18

标签: php mysql sql

我正在使用join plus union plus group by query,我开发了一个类似下面提到的查询:

SELECT *
FROM (
        (SELECT countries_listing.id,
                countries_listing.country,
                1 AS is_country
         FROM countries_listing
         LEFT JOIN product_prices ON (product_prices.country_id = countries_listing.id)
         WHERE countries_listing.status = 'Yes'
           AND product_prices.product_id = '3521')
      UNION
        (SELECT countries_listing.id,
                countries_listing.country,
                0 AS is_country
         FROM countries_listing
         WHERE countries_listing.id NOT IN
             (SELECT country_id
              FROM product_prices
              WHERE product_id='3521')
           AND countries_listing.status='Yes')) AS partss
GROUP BY id
ORDER BY country

我刚刚意识到这个查询花费了大量时间来加载结果,差不多8秒。

我想知道是否有可能将此查询优化为最快的查询?

2 个答案:

答案 0 :(得分:3)

如果我理解逻辑正确,您只想为国家/地区添加一个标志,以确定是否有特定产品的价格。我认为您可以使用exists子句来获得您想要的内容:

SELECT cl.id, cl.country,
       (exists (SELECT 1
                FROM product_prices pp
                WHERE pp.country_id = cl.id AND
                      pp.product_id = '3521'
               )
       ) as is_country
FROM countries_listing cl
WHERE cl.status = 'Yes'
ORDER BY country;

对于性能,您需要两个索引:countries_listing(status, country) product_prices(country_id,product_id)`。

答案 1 :(得分:-1)

根据执行的频率,准备好的陈述可能会有所帮助。有关详细信息,请参阅PDO