简体   繁体   English

带索引的MySQL查询优化器

[英]MySQL Query optimizer with index

i have a database with a lot of ads postings. 我有一个包含大量广告帖子的数据库。 it works fine when the size is small, but now the hosting company suspend my account frequently, because my database have more then 100,000 row. 当大小较小时,它可以正常工作,但是现在托管公司经常暂停我的帐户,因为我的数据库有超过100,000行。 they told me my query is not so efficient for my table anymore. 他们告诉我,我的查询对我的桌子不再那么有效了。 So, i did some search online, and find index might be a way to solve my query issue. 所以,我做了一些在线搜索,找到索引可能是一种解决我的查询问题的方法。

here are query for my site 这是查询我的网站

$sql = "SELECT * 
        FROM `adstable` 
        WHERE `keytype` = '".$cate."' 
        ORDER BY `adstable`.`id` DESC 
        LIMIT 2000";

the $cate will change base on the category visitor select. $ cate将根据访客选择的类别进行更改。 i am using phpmyadmin, and i want to know how the index will work with the query above. 我正在使用phpmyadmin,我想知道索引如何与上面的查询一起工作。 I have create the index for cate column, but don't know how to optimize the query with the index i am created. 我已经为cate列创建了索引,但是不知道如何使用创建的索引来优化查询。

here is how i add the index 这是我如何添加索引

ALTER TABLE  `adstable` ADD INDEX (  `keytype` )

by using 通过使用

EXPLAIN 
SELECT * 
FROM `adstable`
WHERE `keytype` = '".$cate."'
ORDER BY `adstable`.`id` DESC
LIMIT 2000

I got something like this: 我有这样的事情:

id | select_type | table  | type | possible_keys | key     | key_len | ref | rows | Extra
1  | SIMPLE  |adstable| ref  | keytype       | keytype |   38    |const|49392 | Using where; Using filesort

thanks in advance. 提前致谢。

If by cate column you meant keytype column , then your index is already being used. 如果按cate column表示keytype column ,则您的索引已被使用。 Have you noticed any improvement in the query? 您是否注意到查询有任何改善? To check whether the index is really being used in that query you can run the following query: 要检查索引是否确实在该查询中使用,您可以运行以下查询:

EXPLAIN SELECT * FROM `adstable`
WHERE `keytype` = '".$cate."'
ORDER BY `adstable`.`id` DESC
LIMIT 2000

You can post how you created the index and the result of that query to provide more information. 您可以发布创建索引的方式以及该查询的结果以提供更多信息。

  1. Is it a MyISAM table? 它是MyISAM表吗? If yes, add a (keytype, id) index. 如果是,请添加(keytype, id)索引。

  2. If you can lower the 2000 limit to something more sensible, eg if you don't really need 2000 rows, lower that value. 如果你可以将2000限制降低到更合理的范围,例如,如果你真的不需要2000行,那么降低该值。

  3. Do you really need all those columns in the SELECT list? 你真的需要SELECT列表中的所有列吗? If not, remove the * and write down only those columns that you need. 如果没有,请删除*并仅记下您需要的那些列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM