我正在使用join + union + group by查询,并且我开发了一个如下所述的查询:
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秒。
我想知道是否有可能将这个查询优化为最快的查询?
发布于 2015-01-18 23:46:28
如果我没理解错的话,您只是想为国家添加一个标志,说明给定产品是否有价格。我认为您可以使用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)`。
发布于 2015-01-18 23:42:12
根据执行频率的不同,准备好的语句可能会有所帮助。有关详细信息,请参阅PDO。
https://stackoverflow.com/questions/28011506
复制相似问题