0

I have a query:

SELECT `l`.`id`, `l`.`headline`, `l`.`description`, `l`.`image`, `l`.`campaign_id`, IF(l.required_impressions=0,0,1) AS sequence, (IFNULL(ROUND(COUNT(DISTINCT(lc.id)) / COUNT(DISTINCT(li.id)), 3) * 100, 0) * 0.3) + (l.cost * 0.7) AS `scales`, `c`.`name` AS `campaign`
FROM `app_links` AS `l`
INNER JOIN `app_campaigns` AS `c` ON c.id = l.campaign_id
LEFT JOIN `app_link_clicks` AS `lc` ON lc.link_id = l.id
LEFT JOIN `app_link_impressions` AS `li` ON li.link_id = l.id
LEFT JOIN `app_links_categories` AS `lcat` ON l.id = lcat.link_id
LEFT JOIN `app_links_countries` AS `lcou` ON l.id = lcou.link_id
WHERE lcat.category_id IN(3,7,14)
AND lcou.country_id IN(89,147,124,131,259,197,88)
GROUP BY `l`.`id`
ORDER BY sequence DESC, `scales` DESC
LIMIT 6

The EXPLAIN query return: enter image description here

Do you have any ideas how to optimize the query? Now it take ~0.6 sec, so it's quite long :/

4

1 回答 1

2

只要您在子句中引用lcatand ,通过join 将它们连接起来是没有意义的。lcouWHERELEFT

所以我的建议是:

  1. 改变和改变LEFT JOIN_lcatlcouINNER JOIN
  2. 将这 2 个连接上移,使所有INNER JOINs 都在开头
  3. 移动lcatlcou条件到相应的ON子句(这不应该改变任何东西,但会更具可读性)
  4. 创建复合link_id + country_idlink_id + category_id索引
  5. 如您所见 - mysql 优化器更改了表连接的顺序,因此app_links在中间连接,看起来像是app_linksmyisam(这只是基于campaign_id看起来不像聚集索引的事实的猜测)。如果是这样 - 尝试campaign_id + id为它添加复合索引

PS:进行以上修改并提供新的执行计划

PPS:为查询中的所有表提供架构

于 2013-05-15T12:13:54.790 回答