简体   繁体   English

在您选择的列上添加索引会加快查询速度吗?

[英]Does adding an index on the column you are selecting speed up the query?

I have a fairly common setup, I have a table of tags and record pairs. 我有一个相当常见的设置,我有一个标签和记录对的表。 Querying it is slow so adding an index to the column of the tag I am querying helps speed it up. 查询它很慢,因此在我查询的标记列中添加索引有助于加快速度。

tag  | site
123  | 456
789  | 101

My question is whether it is beneficial to add an index on both these columns as one index. 我的问题是,将这两个列的索引添加为一个索引是否有益。 It will never be selected by the site, so is there any benefit to doing this? 它永远不会被网站选中,这样做有什么好处? I also cannot guarantee that each pairing is unique without making some changes but if I did would this help with performance? 我也不能保证每次配对都是独一无二的而不做一些改变但如果我这样做会对性能有帮助吗?

A typical query might look like this: 典型的查询可能如下所示:

SELECT site, tag FROM sitetags WHERE tag ='123' OR tag = '789'

If you always search by tag then you only need to index tag column. 如果您始终按tag搜索,则只需要索引tag列。

Adding column to index when it is not used, introduce unneeded overhead when you insert or update record and also consume more storages. 在未使用时将列添加到索引,在插入或更新记录时会引入不必要的开销,并且还会占用更多存储空间。

But composite index ( tag , site ) may give additional optimization as MySQL only need to read index to satify your query ( EXPLAIN usually marks this optimization as using index ). 但是复合索引( tagsite )可能会提供额外的优化,因为MySQL只需要读取索引来满足您的查询( EXPLAIN通常将此优化标记为using index )。

If your operation is mostly read rather than write, then using composite index may not be a bad idea. 如果您的操作主要是读取而不是写入,那么使用复合索引可能不是一个坏主意。

It will be better if tag column has high cardinality, meaning that there is high chance that their values are different between each rows. 如果tag列具有高基数会更好,这意味着它们的值很可能在每行之间不同。

But I suggest you consult EXPLAIN output first. 但我建议你先咨询EXPLAIN输出。

If these is the only columns that exist in the table, then the answer is no, it won't speed up your query because it will have to process the entire row anyways. 如果这些是表中存在的唯一列,那么答案是否定的,它将不会加快您的查询速度,因为它无论如何都必须处理整个行。

If not, then yes, adding an index on a selected column can speed up the query, because the optimizer will be able to select the value without actually processing the entire row. 如果没有,则是,在所选列上添加索引可以加快查询速度,因为优化器将能够选择该值而不实际处理整行。

Normally, you should index only the columns you filter by. 通常,您应该只索引过滤的列。 I advise to add an index on a selected column only if you actually use this format of select a lot, if not , the disadvantages (such as slow inserts) can overcome the benefits . 我建议在实际使用这种格式选择很多时才在所选列上添加索引,否则,缺点(如慢插入)可以克服这些好处。

Note: Your typical query should actually look like this: 注意:您的典型查询应该看起来像这样:

WHERE tag IN('123','789')

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

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