我有一个查询运行时间特别长(15 秒以上),而且随着我的数据集的增长,它只会随着时间的推移而变得更糟。我过去对此进行了优化,并添加了索引、代码级排序和其他优化,但还需要进一步完善。
SELECT sounds.*, avg(ratings.rating) AS avg_rating, count(ratings.rating) AS votes FROM `sounds`
INNER JOIN ratings ON sounds.id = ratings.rateable_id
WHERE (ratings.rateable_type = 'Sound'
AND sounds.blacklisted = false
AND sounds.ready_for_deployment = true
AND sounds.deployed = true
AND sounds.type = "Sound"
AND sounds.created_at > "2011-03-26 21:25:49")
GROUP BY ratings.rateable_id
Run Code Online (Sandbox Code Playgroud)
该查询的目的是让我获得sound id
最近发布的声音的's 和平均评分。大约有 1500 个声音和 200 万个评分。
我有几个索引 sounds
mysql> show index from sounds;
+--------+------------+------------------------------------------+--------------+----------------------+-----------+-------------+----------+--------+------+------------+————+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part …
Run Code Online (Sandbox Code Playgroud) 我有一个相对较大的 4-deep 关系数据设置,如下所示:
client_applications
: (可能有 1,000 条记录)
- ...
- account_id
-deleted_at
client_application_versions
:(可能有 10,000 条记录)
- ...
- client_application_id
-deleted_at
cloud_logs
:(可能有 1,000,000 条记录)
- ...
- client_application_version_id
-deleted_at
logs
:(可能有 1,000,000,000 条记录)
- ...
- cloud_log_id
- time_stamp
-deleted_at
我仍在开发中,所以结构和设置不是一成不变的,但我认为设置没问题。使用 Rails 3.2.11 和 InnoDB MySQL。数据库充满了一个小的(与最终的数据库大小相比)数据集(logs
只有 700,000 行)我有 4 个查询,其中 3 个有问题,以检索日志。
account_id
, client_application_id
, client_application_version_id
(超过 100 秒)account_id
, client_application_id
(超过 100 秒)account_id
(超过 100 …