简体   繁体   English

在mysql中使用和不使用索引执行查询

[英]executing queries with and without indexes in mysql

I have to run the same queries with and without indexes, in mysql. 我必须在mysql中使用和不使用索引运行相同的查询。 I create indexes like this: 我创建这样的索引:

create index index_1 on table_1(column_name);
create index index_2 on table_2(column_name);

I execute this and I get the results that 0 rows has affected, both times. 我执行此操作,两次都得到0行影响的结果。 Is this ok? 这个可以吗?

Because when I execute the queries I have (after I created indexes), it takes me the same time as before (without indexes.) 因为当我执行查询时(在创建索引之后),它需要与之前相同的时间(没有索引)。

The view of database: 数据库视图: 点击这里查看图片

I have multiple small queries about this database, eg 我有关于这个数据库的多个小查询,例如

SELECT DISTINCT customers.customer_id, customers.customer_name
FROM customers
  INNER JOIN accounts ON customers.customer_id = accounts.customer_id
  INNER JOIN transactions ON transactions.account_id = accounts.account_id 
WHERE transactions.trn_date >= '2011/05/01'
  AND transactions.trn_date <= '2011/05/31'
ORDER BY customers.customer_id

You need these indexes for that query: 您需要为该查询提供以下索引:

transactions: INDEX(trn_date)
accounts:     INDEX(account_id)
customers:    INDEX(customer_id)

In the last two cases, you probably already have that column as the PRIMARY KEY . 在最后两种情况下,您可能已将该列作为PRIMARY KEY If so, do not add a redundant INDEX . 如果是这样,请不要添加冗余INDEX

I execute this and I get the results that 0 rows has affected, both times. 我执行此操作,两次都得到0行影响的结果。 Is this ok? 这个可以吗?

Yes, it is ok. 是的,没关系。
There are DDL operation which create new object and shouldn't output something. 有DDL操作创建新对象,不应输出任何内容。

Because when I execute the queries I have (after I created indexes) it takes me the same time as before (without indexes) 因为当我执行查询时(在创建索引之后),我需要与之前相同的时间(没有索引)

The queries haven't to use index. 查询不得使用索引。 The internal optimizer make decision in depend of data distribution. 内部优化器根据数据分布做出决策。 For example, if column_name.table_1 has 50 unique values, then index is not be used. 例如,如果column_name.table_1有50个唯一值,则不使用index。

More details ou can found in official documentation: 9.3.1 How MySQL Uses Indexes 更多详细信息可以在官方文档中找到: 9.3.1 MySQL如何使用索引

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

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