考虑此查询:
select d.*
from data d
where channel_id=83
order by channel_id,timestamp
执行立即执行,因为channel_id,时间戳被索引:
CREATE TABLE `data` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`channel_id` int(11) DEFAULT NULL,
`timestamp` bigint(20) NOT NULL,
`value` double NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `data_unique` (`channel_id`,`timestamp`),
KEY `IDX_ADF3F36372F5A1AA` (`channel_id`),
CONSTRAINT `FK_ADF3F36372F5A1AA` FOREIGN KEY (`channel_id`) REFERENCES `entities` (`id`)
)
一旦我添加了一个简单的LAG(),查询就会变得缓慢:
select d.*
,lag(value) over (order by channel_id,timestamp)
from data d
where channel_id=83
order by channel_id,timestamp
说明计划:
+------+-------------+-------+------+----------------------------------+----------------------+---------+-------+--------+-----------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+------+-------------+-------+------+----------------------------------+----------------------+---------+-------+--------+-----------------+
| 1 | SIMPLE | d | ref | data_unique,IDX_ADF3F36372F5A1AA | IDX_ADF3F36372F5A1AA | 5 | const | 759654 | Using temporary |
+------+-------------+-------+------+----------------------------------+----------------------+---------+-------+--------+-----------------+
在没有LAG()语句的情况下说明计划:
+------+-------------+-------+------+----------------------------------+----------------------+---------+-------+--------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+------+-------------+-------+------+----------------------------------+----------------------+---------+-------+--------+-------+
| 1 | SIMPLE | d | ref | data_unique,IDX_ADF3F36372F5A1AA | IDX_ADF3F36372F5A1AA | 5 | const | 759730 | |
+------+-------------+-------+------+----------------------------------+----------------------+---------+-------+--------+-------+
mariadb中的窗口函数是否存在性能问题,还是我的查询错误?