amr*_*ree 13 mysql database-design
表结构:
+-------------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+----------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| total | int(11) | YES | | NULL | |
| thedatetime | datetime | YES | MUL | NULL | |
+-------------+----------+------+-----+---------+----------------+
Run Code Online (Sandbox Code Playgroud)
总行数:137967
mysql> explain select * from out where thedatetime <= NOW();
+----+-------------+-------------+------+---------------+------+---------+------+--------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------------+------+---------------+------+---------+------+--------+-------------+
| 1 | SIMPLE | out | ALL | thedatetime | NULL | NULL | NULL | 137967 | Using where |
+----+-------------+-------------+------+---------------+------+---------+------+--------+-------------+
Run Code Online (Sandbox Code Playgroud)
对于更多的表连接,真正的查询要长得多,重点是,我无法让表使用datetime索引.如果我想在特定日期之前选择所有数据,这对我来说将很难.但是,我注意到如果选择较小的数据子集,我可以让MySQL使用索引.
mysql> explain select * from out where thedatetime <= '2008-01-01';
+----+-------------+-------------+-------+---------------+-------------+---------+------+-------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------------+-------+---------------+-------------+---------+------+-------+-------------+
| 1 | SIMPLE | out | range | thedatetime | thedatetime | 9 | NULL | 15826 | Using where |
+----+-------------+-------------+-------+---------------+-------------+---------+------+-------+-------------+
mysql> select count(*) from out where thedatetime <= '2008-01-01';
+----------+
| count(*) |
+----------+
| 15990 |
+----------+
Run Code Online (Sandbox Code Playgroud)
那么,无论我放在什么日期,我还能做些什么来确保MySQL使用索引?
Era*_*rin 13
这里有两件事 -
指数不够有选择性 - 如果指数覆盖超过约.30%的行,MySQL将决定全表扫描更高效.当您收缩该范围时,该指数就会开始.
连接中每个表的一个索引
对于更多的表连接,真正的查询要长得多,重点是......
关键是因为它有连接,它可能无法使用该索引.MySQL可以在连接中为每个表使用一个索引(除非它有资格进行索引合并优化).如果主键已用于连接,则不会使用日期时间.要使用它,您需要以正确的顺序在连接键+ thedatetime索引上创建多列索引.
检查实际查询的EXPLAIN以查看MySQL用于连接的密钥.修改该索引以包含thedatetime列,或者从两者创建新的多列索引(取决于您使用连接键的内容).
| 归档时间: |
|
| 查看次数: |
13754 次 |
| 最近记录: |