-mariadb 在 Linux 4core 8 gig ram vps 野兽上
我尝试以下选择语句。
SELECT *
from Sensorwerte
WHERE (Datum>='2023-10-01 00'
and Datum <='2023-10-15 00'
AND (Datum LIKE '%15:00.000'))
AND SensorNr=3004
ORDER BY ID DESC;
/* Betroffene Zeilen: 0 Gefundene Zeilen: 335 Warnungen: 0 Dauer von 1 Abfrage: 2,313 Sek. */
2.3秒后回答,持续15天
但是 30 天:
SELECT *
from Sensorwerte
WHERE (Datum>='2023-10-01 00'
and Datum <='2023-10-30 00'
AND (Datum LIKE '%15:00.000'))
AND SensorNr=3004
ORDER BY ID DESC;
/* Betroffene Zeilen: 0 Gefundene Zeilen: 696 Warnungen: 0 Dauer von 1 Abfrage: 29,594 Sek. (+ 55,297 Sek. Netzwerk) */
84秒后答复,持续30天
我的意思是双倍可以〜5秒,但84秒不行。 有什么问题或者我如何在服务器或 sql select 上调整它?
你有什么想法吗?
SELECT *
from Sensorwerte
WHERE (Datum>='2023-10-01 00'
AND Datum <='2023-10-15 00')
AND SensorNr=3004
ORDER BY ID DESC;
没有 LIKE 15 天 --> 14 秒
显示创建表Sensorwerte
CREATE TABLE `Sensorwerte`
(`ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`Datum` datetime(3) NOT NULL,
`SensorNr` smallint(6) NOT NULL,
`Wert` decimal(15,5) DEFAULT NULL,
PRIMARY KEY (`ID`),
KEY `Zeit` (`Datum`)) ENGINE=InnoDB AUTO_INCREMENT=52208193 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
分析陈述答案
select_type=simple,
table=sensorwerte,
type=index,
possible_keys=zeit,
key=primary,
key_len=4,
ref=(NULL),
rows=48615830,
r_rows=51973599.00,
filtered=31,65,
r_filtered=0,
extra=using where
对于大多数传感器数据查询来说,这是有益的
INDEX(SensorNr, Datum)
(如果你也有的话,请删除它:
INDEX(SensorNr)
添加索引。由于
SensorNr
是一个固定值,请将其放在 Datum
之前。然后查询就可以使用这个索引来进行搜索的所有部分。
ALTER TABLE Sensorwerte ADD KEY newKey(`SensorNr`,`Datum`);
处理日期时,使用 datetime 函数,如
time(Datum) = '15:00.000'
,而不是字符串函数。
查询计划:
MariaDB [test]> explain format=json SELECT * from Sensorwerte WHERE (Datum>='2023-10-01' and Datum <='2023-10-30 00' AND time(Datum) = '15:00.000') and SensorNr=3007 ORDER BY ID DESC\G
*************************** 1. row ***************************
EXPLAIN: {
"query_block": {
"select_id": 1,
"read_sorted_file": {
"filesort": {
"sort_key": "Sensorwerte.`ID` desc",
"table": {
"table_name": "Sensorwerte",
"access_type": "range",
"possible_keys": ["newKey", "Zeit"],
"key": "newKey",
"key_length": "9",
"used_key_parts": ["SensorNr", "Datum"],
"rows": 69,
"filtered": 0.0069,
"index_condition": "Sensorwerte.SensorNr = 3007 and Sensorwerte.Datum >= '2023-10-01' and Sensorwerte.Datum <= '2023-10-30 00' and cast(Sensorwerte.Datum as time(3)) = '15:00.000'"
}
}
}
}
}
1 row in set (0.002 sec)