我编写了一个 SQL 例程,用于根据 5 天的数据(这些天是例程的参数)计算一天中每一分钟的平均值,并将结果插入另一个表中。它很长,我想知道是否有任何方法可以优化它。
我需要用来计算平均值的值都在同一个表 SiteReading 中,因此要获得同一分钟的 5 个值,但从不同的日子开始,我加入了那些日子的表子集,因此小时和分钟将匹配,然后值最终位于同一行。然后我在每一行上添加 5 个值,并从中创建一个新表,并将其插入到存储这些平均值的基线表中。
这是例程:
CREATE PROCEDURE 'calc_baseline` (IN `input_site_id` int, IN `day1` varchar(12), IN `day2` varchar(12), IN `day3` varchar(12), IN `day4` varchar(12), IN `day5` varchar(12))
BEGIN
insert into Baseline
SELECT
site_id,
contract_id,
temp_time as timestamp,
(sr1value + sr2value + sr3value + sr4value + sr5value) / 5 as value,
programme
FROM
(SELECT
distinct concat(cast(hour(temp_time) as char), ':', cast(minute(temp_time) as char)) as hourminute,
SR.site_id as site_id,
value as sr1value,
temp_time,
S.contract_id as contract_id,
programme
FROM
SiteReading SR
join Site S ON SR.site_id = S.site_id
join Contract C ON S.contract_id = C.contract_id
where
temp_time like 'day1%'
and SR.site_id = input_site_id) sr1
join
(SELECT
concat(cast(hour(temp_time) as char), ':', cast(minute(temp_time) as char)) as hourminute,
value as sr2value
FROM
SiteReading
where
temp_time like 'day2%'
and site_id = input_site_id) sr2 ON sr1.hourminute = sr2.hourminute
join
(SELECT
concat(cast(hour(temp_time) as char), ':', cast(minute(temp_time) as char)) as hourminute,
value as sr3value
FROM
SiteReading
where
temp_time like 'day3%'
and site_id = input_site_id) sr3 ON sr1.hourminute = sr3.hourminute
join
(SELECT
concat(cast(hour(temp_time) as char), ':', cast(minute(temp_time) as char)) as hourminute,
value as sr4value
FROM
SiteReading
where
temp_time like 'day4%'
and site_id = input_site_id) sr4 ON sr1.hourminute = sr4.hourminute
join
(SELECT
concat(cast(hour(temp_time) as char), ':', cast(minute(temp_time) as char)) as hourminute,
value as sr5value
FROM
SiteReading
where
temp_time like 'day5%'
and site_id = input_site_id) sr5 ON sr1.hourminute = sr5.hourminute
limit 1440;
END//
DELIMITER ;
它正在读取和写入的相关表是:
- 现场阅读:
CREATE TABLE `SiteReading` (
`site_id` int(11) NOT NULL,
`contract_id` int(11) DEFAULT NULL,
`temp_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`value` int(11) NOT NULL,
PRIMARY KEY (`site_id`,`temp_time`),
KEY `site_id` (`site_id`),
KEY `contract_id` (`contract_id`),
CONSTRAINT `SiteReading_ibfk_1` FOREIGN KEY (`site_id`) REFERENCES `Site` (`site_id`),
CONSTRAINT `SiteReading_ibfk_3` FOREIGN KEY (`contract_id`) REFERENCES `Contract` (`contract_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$
- 基线:
CREATE TABLE `Baseline` (
`site_id` int(11) NOT NULL,
`contract_id` int(11) NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`value` int(11) NOT NULL,
`programme` int(11) NOT NULL,
PRIMARY KEY (`site_id`,`timestamp`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$
因为我需要获取一些附加值(site_id、contract_id、program)来存储在基线中,这些值对于每一行都是相同的,所以我想知道也许我应该以其他方式执行插入语句?问题是基线表的所有列都不能为空。
也许有人对此过程有任何其他评论 - 我是否需要为此例程定义一些其他参数,例如 ON DUPLICATE KEY UPDATE 或其他一些与例程相关的事情?
谢谢。