我有一个 MySQL(实际上是 MariaDB)查询,当我尝试按 DATETIME 字段(sighted
)而不是主键排序时,该查询运行速度要慢得多,并且会回退到文件排序。我在 sighted
上有一个索引,但由于某种原因它似乎没有使用它。如何为该表建立索引,以便可以按 DATETIME 字段有效地对其进行排序?
select
user_id , t.name, f.value, y.name
from posts p
left join taxon_sightings t on (t.post_id = p.id)
left join fields f on (f.foreign_id = t.id)
left join fieldtypes y on (y.id = f.fieldtype_id)
group by p.id
order by p.sighted desc
limit 10;
当我按sighted
DATETIME 字段排序时:
MariaDB [dbase]> explain [yadda yadda, as above]
+----+-------------+-------+--------+---------------+------------+---------+--------------------------------+------+---------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+---------------+------------+---------+--------------------------------+------+---------------------------------+
| 1 | SIMPLE | p | ALL | NULL | NULL | NULL | NULL | 1759 | Using temporary; Using filesort |
| 1 | SIMPLE | t | ref | post_id | post_id | 4 | dataportal_test.p.id | 12 | |
| 1 | SIMPLE | f | ref | foreign_id | foreign_id | 4 | dataportal_test.t.id | 6 | Using where |
| 1 | SIMPLE | y | eq_ref | PRIMARY | PRIMARY | 4 | dataportal_test.f.fieldtype_id | 1 | Using where |
+----+-------------+-------+--------+---------------+------------+---------+--------------------------------+------+---------------------------------+
与按 ID 排序时相比:
+----+-------------+-------+--------+---------------+------------+---------+--------------------------------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+---------------+------------+---------+--------------------------------+------+-------------+
| 1 | SIMPLE | p | index | NULL | PRIMARY | 4 | NULL | 1 | |
| 1 | SIMPLE | t | ref | post_id | post_id | 4 | dataportal_test.p.id | 12 | |
| 1 | SIMPLE | f | ref | foreign_id | foreign_id | 4 | dataportal_test.t.id | 6 | Using where |
| 1 | SIMPLE | y | eq_ref | PRIMARY | PRIMARY | 4 | dataportal_test.f.fieldtype_id | 1 | Using where |
+----+-------------+-------+--------+---------------+------------+---------+--------------------------------+------+-------------+
最佳答案
我认为你做不到。我能想到的唯一技巧就是尝试这个:
select user_id, t.name, f.value, y.name
from posts p left join
taxon_sightings t
on (t.post_id = p.id) left join
fields f
on (f.foreign_id = t.id) left join
fieldtypes y
on (y.id = f.fieldtype_id)
group by p.sighted, p.id
---------^ very important
order by p.sighted desc
limit 10;
然后在 posts(sighted, id)
上添加索引。 group by
和 order by
可能会利用索引。如果你幸运的话。 。 .
关于mysql - 按日期时间排序时,大量连接的 MySQL 查询会变慢,而按 ID 排序则不会变慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31061628/