简体   繁体   中英

How to optimize MYSQL inner query

I have one table named table1 and I want to join its sum based on its 'MEMBER_LEVEL_STRING'

I wrote this query this is working but it is taking 1 hr for 40 thousand records, how can i optimize this query?

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`;

This is your query:

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;

It looks like you are trying to sum up values in a tree structure. You might try adding the index: table1(B_LEVEL, MEMBER_LEVEL_STRING, PP) . This might help.

I believe this query does the same as yours

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')

The 'zzzzzz' needs to be replaced with something that is guaranteed to be higher than any of the suffixes of the higher-level MEMBER_LEVEL_STRING.

Depending on the contents of your table, you may then try an index on either (B_LEVEL,MEMBER_LEVEL_STRING) or (MEMBER_LEVEL_STRING,B_LEVEL) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM