Cod*_*ary 2 mysql query-optimization
我是数据库查询优化的新手.这是创建表查询:
CREATE TABLE mo (
id int UNSIGNED NOT NULL auto_increment,
msisdn varchar(20) NOT NULL,
operatorid int UNSIGNED NOT NULL,
shortcodeid int UNSIGNED NOT NULL,
text varchar(100) NOT NULL,
auth_token varchar(60) NOT NULL,
created_at DATETIME,
PRIMARY KEY(id)
);
Run Code Online (Sandbox Code Playgroud)
我的查询是这样的:
SELECT count(id) as mo_count from mo where created_at > DATE_SUB(NOW(), INTERVAL 15 MINUTE)
Run Code Online (Sandbox Code Playgroud)
当我测试它时,结果是
Time taken for tests: 3.50 seconds
[0] => Array
(
[id] => 1
[select_type] => SIMPLE
[table] => mo
[type] => ALL
[possible_keys] =>
[key] =>
[key_len] =>
[ref] =>
[rows] => 10000255
[Extra] => Using where
)
Run Code Online (Sandbox Code Playgroud)
请教我如何优化此查询.非常感谢.
您需要INDEX在用于该查询的列上添加一个,否则数据库必须检查表中的所有行以查看哪个行符合您的WHERE子句.
ALTER TABLE mo ADD INDEX (created_at);
Run Code Online (Sandbox Code Playgroud)
该index给MySQL来只扫描表的一部分,根据您在该列有数据的能力.
您可以阅读有关mysql如何使用索引的更多信息.
关于查询本身 - 没有改变你的表的结构你不能真正优化它(除非你知道哪个ids适合WHERE你,你可以改变查询使用id> X,因为id你的表中的列被索引,但我想它不是真的如此).
| 归档时间: |
|
| 查看次数: |
548 次 |
| 最近记录: |