如何优化MYSQL内部查询

时间:2014-08-02 13:40:21

标签: mysql sql substring query-optimization database-performance

我有一个名为table1的表,我希望根据'MEMBER_LEVEL_STRING'加入其总和

我写了这个查询这是有效但是4万条记录需要1小时,我该如何优化这个查询?

SELECT `p`.`MEMBER_ID` AS `MEMBER_ID`,
    (
        SELECT SUM(`ip`.`PP`) 
        FROM `table1` `ip`
        WHERE ip.B_LEVEL >= p.B_LEVEL AND
            `p`.`MEMBER_LEVEL_STRING` = SUBSTRING(ip.MEMBER_LEVEL_STRING,1,LENGTH(p.MEMBER_LEVEL_STRING))
    )
    AS `GPP`
FROM `table1` `p`;

2 个答案:

答案 0 :(得分:0)

这是您的查询:

SELECT p.MEMBER_ID AS MEMBER_ID,
       (SELECT SUM(ip.PP)
        FROM table1 ip
        WHERE ip.B_LEVEL >= p.B_LEVEL AND
              p.MEMBER_LEVEL_STRING = SUBSTRING(ip.MEMBER_LEVEL_STRING, 1,
                                                LENGTH(p.MEMBER_LEVEL_STRING)
                                               )
       ) AS GPP
FROM table1 p;

看起来您正在尝试在树结构中总结值。您可以尝试添加索引:table1(B_LEVEL, MEMBER_LEVEL_STRING, PP)。这可能有所帮助。

答案 1 :(得分:0)

我相信此查询与您的查询相同

SELECT p.MEMBER_ID,SUM(ip.PP)
    FROM table1 p
    JOIN table1 ip
    ON ip.B_LEVEL>=p.B_LEVEL AND
       ip.MEMBER_LEVEL_STRING BETWEEN
           p.MEMBER_LEVEL_STRING AND
           CONCAT(p.MEMBER_LEVEL_STRING,'zzzzzzz')

' zzzzzz'需要替换为保证高于更高级别MEMBER_LEVEL_STRING的任何后缀的内容。

根据表格的内容,您可以尝试(B_LEVEL,MEMBER_LEVEL_STRING)(MEMBER_LEVEL_STRING,B_LEVEL)上的索引。