大规模查询的优化

时间:2016-06-24 08:45:07

标签: mysql query-optimization

我有以下查询,用于创建用户填写信息的百分比。我将其存储为视图,但查询大约需要6分钟才能运行1500个用户。如何加快查询速度?

它将用作在用户处于非活动状态时每天运行一次的查询。我们目前正在迅速扩大用户群,我只是担心15,000个用户会出错。

请MySQL大师,求求你的帮助!

CREATE VIEW profile_check AS(
SELECT users.id, 
    FORMAT(( IF(
        COUNT(users.firstname)+ 
        COUNT(users.lastname)+ 
        COUNT(users.gender)+
        COUNT(users.country)+
        COUNT(users.address_one)+
        COUNT(users.city)+
        COUNT(users.zipcode)+
        COUNT(users.housenumber)+
        COUNT(users.phonenumber)+
        COUNT(users.educationlevel_id) = 10, 1, 0) +
    IF(
        COUNT(assesspassionresults.user_id) > 0, 1, 0) +
    IF(
        COUNT(assessmentcompetencyresults.user_id) > 0, 1, 0) +
    IF(
        COUNT(assessmentstrengthresults.user_id) > 0, 1, 0) +
    IF(
        SUM(CASE WHEN timelines.component_of = "employer" THEN 1 ELSE 0 END) > 0, 1, 0) +
    IF(
        SUM(CASE WHEN timelines.component_of = "individual" THEN 1 ELSE 0 END) > 0, 1, 0) +
    IF(
        COUNT(interests.user_id) > 0, 1, 0) +
    IF(
        COUNT(skills.user_id) > 0, 1, 0) +
    IF(
        COUNT(users_mediafiles.user_id) > 0, 1, 0) ) / 9 , 0) as profiel_check
FROM users
LEFT JOIN assesspassionresults
    ON users.id = assesspassionresults.user_id
LEFT JOIN assessmentcompetencyresults
    ON users.id = assessmentcompetencyresults.user_id
LEFT JOIN assessmentstrengthresults
    ON users.id = assessmentstrengthresults.user_id
LEFT JOIN timelines
    ON users.id = timelines.user_id
LEFT JOIN interests
    ON users.id = interests.user_id
LEFT JOIN skills
    ON users.id = skills.user_id
LEFT JOIN users_mediafiles
    ON users.id = users_mediafiles.user_id
GROUP BY users.id);

EXPLAIN

enter image description here

1 个答案:

答案 0 :(得分:0)

正如MySQL大师的建议,在所有user_id列上添加索引可以解决我的性能问题。它确实做到了!

ALTER TABLE assesspassionresults ADD INDEX (user_id);
ALTER TABLE assessmentcompetencyresults ADD INDEX (user_id);
ALTER TABLE assessmentstrengthresults ADD INDEX (user_id);
ALTER TABLE timelines ADD INDEX (user_id);
ALTER TABLE skills ADD INDEX (user_id);
ALTER TABLE users_mediafiles ADD INDEX (user_id);
ALTER TABLE interests ADD INDEX (user_id);