【发布时间】:2020-12-09 15:49:39
【问题描述】:
我正在尝试解决此表的性能问题
+--------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| direction_id | int(10) unsigned | NO | MUL | NULL | |
| created_at | datetime | NO | | NULL | |
| rate | decimal(16,6) | NO | | NULL | |
+--------------+------------------+------+-----+---------+----------------+
其中包含大约 1 亿行
只有一个查询从该表中选择数据:
SELECT AVG(rate) AS rate, created_at
FROM statistics
WHERE direction_id = ?
AND created_at BETWEEN ? AND ?
GROUP BY created_at
direction_id 是外键,但选择性很差:
+----+-------------+------------+------------+------+---------------------------------+---------------------------------+---------+-------+-------+----------+---------------------------------------------------------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+------------+------------+------+---------------------------------+---------------------------------+---------+-------+-------+----------+---------------------------------------------------------------------+
| 1 | SIMPLE | statistics | NULL | ref | statistics_direction_id_foreign | statistics_direction_id_foreign | 4 | const | 26254 | 11.11 | Using index condition; Using where; Using temporary; Using filesort |
+----+-------------+------------+------------+------+---------------------------------+---------------------------------+---------+-------+-------+----------+---------------------------------------------------------------------+
所以我正在寻找一种方法来解决这个问题并需要建议。 HASH(direction_id) 分区对我有帮助吗? 如果有帮助,最好的方法是什么?
或者也许有其他方法可以解决它。
【问题讨论】:
-
YEAR(created_at), MONTH(created_at), DAY(created_at)嗯? -
@Strawberry 没关系,我觉得可以省略
标签: mysql sql datetime query-optimization where-clause