使用子查询优化MySQL查询

时间:2014-07-02 08:26:12

标签: mysql

优化此查询的最佳方法是什么?是否可以生成索引?没有优化就需要8秒。

SELECT
    partner_banner_views AS views,
    (
      SELECT
        count(statistics_partner_id)
      FROM
        statistics_partner
      WHERE
        statistics_partner_partner_id = partner_id
      AND statistics_partner_click_date IS NOT NULL
    ) AS clicks,
    round (
    (
        100 *(
            SELECT
                count(statistics_partner_id)
            FROM
                statistics_partner
            WHERE
                statistics_partner_partner_id = partner_id
            AND statistics_partner_click_date IS NOT NULL
        )/ partner_banner_views
    ),
    3
) AS ctr
FROM partners

THX

1 个答案:

答案 0 :(得分:1)

如果您希望有大量statistics_partner_partner_id点击日期,则需要statistics_partner_partner_id,statistics_partner_click_dateNULL上的索引。

您可以将其转换为JOIN,如下所示:

SELECT
    partner_banner_views AS views,
    COUNT(statistics_partner_partner_id) as clicks,
    ROUND(100 * clicks / COUNT(statistics_partner_partner_id), 3) as ctr
FROM partners
LEFT JOIN statistics_partner ON statistics_partner_partner_id = partner_id 
                                AND statistics_partner_click_date IS NOT NULL
GROUP BY partner_id