sql 自连接 优化

需求

有一年的测点的时序数据(累计值),每小时一个值。现计算测点每个小时的差值(例如 2点值 - 1点值)

表结构

create table  
(
      `tagname` varchar(255) default null,
      `time` varchar(255) default null,
      `value` float,
      KEY `time` (`time`) using betree,
      KEY `name` (`tagname`) using hash
)engine = innodb;

优化之前语句

select 
	a.tagname,
	a.time,
	b.value -a.value as value
from
	source_dnla a,
	source_dnla b
where
	a.tagname=b.tagname
	and timestampdiff(HOUR,b.time,a.time) = 1
order by 
	a.time;

优化之后的语句

select 
	a.tagname,
	a.time,
	b.value -a.value as value
from
	(select *,DATE_ADD(time,INTERVAL 1 HOUR) as next_time from source_dnla) a,
	source_dnla b
where 
	a.tagname = b.tagname
	and a.next_time = b.time
order by
	a.time;

总结

优化之前由于需要判断时间相差一小时而使用了函数,导致在时间上的索引失效。查询缓慢。优化思路是增加一列表示需要join 的列,然后进行

join。此时就不需要对时间进行函数计算。索引生效。查询更快。

如果join时候因为join 条件需要计算而破坏索引,可以通过提前将join 条件计算出来。然后再join 的方法让索引生效

金钱和自由相比,不值一提
原文地址:https://www.cnblogs.com/roadzhao/p/14109949.html