我有以下查询:
SELECT
shows.id,
shows.title,
shows.thumbnail,
shows.views,
shows.likes,
shows.dislikes,
shows.duration,
shows.hd,
shows.origin,
UNIX_TIMESTAMP(shows.upload_date) as upload_date
FROM
shows
WHERE
(shows.views, shows.id) < (0, 272990)
and shows.visible = 1
ORDER BY
shows.views DESC,
shows.id DESC
LIMIT
32
在 MySQL 8.0.15 中大约需要 0.8 秒。
我试过这样的索引:
CREATE INDEX views_desc_id_desc_visible ON shows (views desc, id desc, visible)
以及像这样的:
CREATE INDEX views_desc_id_desc ON shows (views desc, id desc)
和许多其他排列。我已经删除了它们并从头开始重做了很多次。Visible 本身确实有一个索引。
当我进行解释时,我看到它只在使用名为views_desc_id_desc_visible 的键时执行“使用位置”。从查询中删除可见并不会改变它的性能。删除两个 desc (因此:按视图排序,id)确实使它成为 0.0008 秒。
为什么这不快点?
更新 (从评论复制)
SELECT shows.id, shows.title, shows.thumbnail, shows.views, shows.likes,
shows.dislikes, shows.duration, shows.hd, shows.origin,
UNIX_TIMESTAMP(shows.upload_date) as upload_date
FROM shows
WHERE (shows.views <= 0)
and not (shows.views = 0 and shows.id >= 272990)
and visible = 1
ORDER BY shows.views DESC, shows.id DESC
LIMIT 32
修复它。我只是不知道为什么以其他方式使用会忽略索引。