简体   繁体   中英

MySql: sum value based on state field on millions rows table

I have a table with millions of rows (SF_COLLECTIONS)

ID MEMBERID COLLECTIONID CARDID STATE (D / M) HOWMANY
1  1        1            1      D             1
2  1        1            2      D             2
3  2        1            1      M             1
4  2        1            2      M             1
5  2        2            3      D             1
6  1        2            3      M             2

and I want to know for every COLLECTIONID the SUM of HOWMANY field for STATE=D and STATE=M So I try this approach

select COLLECTIONID,
sum(if(STATE='D',HOWMANY,0)) as HMD,
sum(if(STATE='M',HOWMANY,0)) as HMM
from SF_COLLECTIONS
group by COLLECTIONID

and it takes about 15 seconds to answer

Any suggestions to get better performances?

Thanks in advance

Please try this:

SELECT COLLECTIONID,
SUM(CASE WHEN STATE='D' THEN HOWMANY END) AS HMD,
SUM(CASE WHEN STATE='M' THEN HOWMANY END) AS HMM
FROM SF_COLLECTIONS
GROUP BY COLLECTIONID;

Duration / Fetch Time
0.00068 sec / 0.000012 sec

Your existing_query:

SELECT COLLECTIONID,
SUM(IF(STATE='D',HOWMANY,0)) AS HMD,
SUM(IF(STATE='M',HOWMANY,0)) AS HMM
FROM SF_COLLECTIONS
GROUP BY COLLECTIONID;

Duration / Fetch Time
0.00072 sec / 0.000012 sec

Only 6 rows there is 0.00004 difference: For 10 million rows, I think It is noticeable:)

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