I need ideas to optimize this query:
SELECT U.Id
, U.Name
, SUM(P.Credit) AS CreditAmount
, SUM(P.Debit) AS DebitAmount
FROM users U
LEFT JOIN payments P ON P.UserId = U.Id
WHERE U.StatusId = 1 /* Active Users Only */
GROUP BY U.Id
Some information about the tables:
userstable: 10,000+ recordspaymentstable: 2,000,000+ records, indexed onUserIdcolumn
The query takes up to 2 minutes. By investigating the query, I found out that the SUM function is the reason why the query is slow. Tried executing the query without the SUM takes less than 2 seconds.
Is there any room to improve this query? Thanks
EDIT 1
This is what I got when using the EXPLAIN:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE U ALL 8304 Using where; Using temporary; Using filesort
1 SIMPLE P ref UserId UserId 5 Database.U.Id 361 ""
The index payments.UserId is being used in the query. Any thoughts on this?
EDIT 2
Table Information:
users "CREATE TABLE `users` (
`Id` int(11) NOT NULL auto_increment,
`StatusId` int(11) default NULL,
`Name` varchar(60) default NULL,
`TimeZone` varchar(100) default NULL,
PRIMARY KEY (`Id`),
KEY `StatusId` (`StatusId`),
CONSTRAINT `FK_User_Status` FOREIGN KEY (`StatusId`) REFERENCES `userStatus` (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8"
payments "CREATE TABLE `payments` (
`Id` int(11) NOT NULL auto_increment,
`UserId` int(11) default NULL,
`Description` varchar(200) default NULL,
`Debit` decimal(11,2) default NULL,
`Credit` decimal(11,2) default NULL,
`Date` datetime default NULL,
PRIMARY KEY (`Id`),
KEY `UserId` (`UserId`),
CONSTRAINT `FK_Payment_User` FOREIGN KEY (`UserId`) REFERENCES `users` (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8"
According this link, I can’t speed up the
SUMfunction. The main issue here is that I’m selecting a huge number of records.I thought of redesigning the
userstable, adding a new column likeTotalPaymentwhich will hold the totalcreditminusdebitamount from thepaymentstable. I know it disobeys the database normalization rules, but I guess this redesign is for saving performance.Thanks a lot for your help guys.