如何使用WHERE、RANGE和SORT设置MySql表的索引?
我有一个MySql表和查询,我正在尝试优化它,并且有一些问题如何使用WHERE、RANGE和SORT设置MySql表的索引?,mysql,optimization,indexing,Mysql,Optimization,Indexing,我有一个MySql表和查询,我正在尝试优化它,并且有一些问题 SELECT value FROM table WHERE userid=?userid AND date <= ?date AND deleted='False' ORDER BY date DESC LIMIT 1 我得到以下查询的解释结果: id select_type table type possible_keys key key_len ref
SELECT value FROM table WHERE userid=?userid AND date <= ?date AND deleted='False' ORDER BY date DESC LIMIT 1
我得到以下查询的解释结果:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE table ref userid_date userid_date 5 const 4 Using where; Using filesort
如果我在userid\u date key userid\u date userid中更改为同时使用date,则会得到以下解释结果:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE table range userid_date userid_date 9 NULL 4 Using where
这更好,因为它不使用filesort,但它的类型似乎不如仅使用userid作为键时好。如何设置表和查询的索引?使用日期类型作为索引好吗
这更好,因为它不使用filesort
是的,因为索引中还有一个可用的过滤器
您还可以考虑添加删除的userid、deleted、date。但是,请确保相等比较位于range和order by子句所用的列之前,否则将返回排序
但它的类型似乎不如仅使用userid时好
为什么??我认为你的指数会足够好。删除的列可能不值得,可能只是浪费空间。但这取决于其他查询是否也使用该列,以及数据库中的“错误”率
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE table range userid_date userid_date 9 NULL 4 Using where