I am trying to get the results between two dates with SUM, but it is taking long time to execute multiple queries in a Loop. Below is my Query.

Database table contains more than 1.5L records and this count will increase going forward. And also executing multiple queries in a loop.

below is my query:

SELECT TIME_FORMAT( SEC_TO_TIME( SUM( TIME_TO_SEC( run_hours ) ) ) , '%H:%i:%s' ) AS total_time
FROM excel_info
WHERE indus_id = 'IN-1086331' AND (date_time BETWEEN '2008-11-27' AND '2013-05-04')

Database Table Structre:

CREATE TABLE IF NOT EXISTS `excel_info` (
   `id` bigint(20) NOT NULL AUTO_INCREMENT,
   `indus_id` varchar(20) NOT NULL,
   `district` varchar(50) NOT NULL,
   `date_time` date NOT NULL,
   `run_hours` varchar(100) NOT NULL,
   `flag` varchar(100) NOT NULL,
   PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1844417 ;

Thanks in Advance.

有帮助吗?

解决方案

Add an index that includes the columns you're filtering on:

CREATE INDEX ix_indus_dt ON `excel_info` (`indus_id`, `date_time`);

Also, calling TIME_TO_SEC on every matching row will be expensive. You could store run_hours as an integer instead.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top