查询需要很长时间

问题描述

SELECT  a.sectionid as sectionid,views.timestamp as timestamp,views.time_on_page as time_on_page,views.video as video,views.access as access,masterid
    FROM (
        SELECT  m.timestamp as timestamp,m.time_on_page as time_on_page,AES_DECRYPT(m.IP_Blob,UNHEX(SHA2('Jove Is Cool',512))) as ip_bin,m.page as page,m.language as language,m.access as access,m.referrer as referrer,m.searchterms as searchterms,m.user_id as user_id,case when m.page regexp '/pdf(-materials)?/'
                     then replace(replace(replace(RIGHT(m.page,5),'/',''),'d','f','')
                     else m.video end as video,m.id as masterid
            FROM  masterstats_innodb as m
            join  stats_to_institution as sti  ON m.id = sti.statid
            JOIN  institutions as ins  ON sti.institutionid = ins.institutionid
            WHERE  m.timestamp BETWEEN '2019-12-30' AND '2020-12-29'
              and  ( ins.institutionid = '2'
                  or ins.parentinstitutionid = '2' ) 
        ) as views
    LEFT JOIN  articles as a  ON views.video = a.productid
       `enter code here`
    order by masterid

masterstats_innodb -- 115759655 stats_to_institution -- 45317238 机构--45038

已为 masterstats_innodb 表创建了所有可能的索引并创建了分区。

解决方法

OR 没有优化好;切换到 UNION 是一种常见的解决方法。但尚不清楚这是否会有所帮助。哪个更有选择性? m.timestamp 还是 (ins.institutionid = '2' or ins.parentinstitutionid = '2')

对于 stats_to_institution 上的最佳索引:http://mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table

enter code here 在哪里没有意义;请填写示例。

暂定索引:

a:  (productid,sectionid)
ins:  (parentinstitutionid,institutionid)
m:  (timestamp)
sti:  (statid,institutionid)
sti:  (institutionid,statid)