在mysql

时间:2016-05-12 10:44:01

标签: mysql sql indexing database-indexes

我必须在mysql中使用和不使用索引运行相同的查询。 我创建这样的索引:

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

我执行此操作,两次都得到0行影响的结果。这可以吗?

因为当我执行查询时(在创建索引之后),我需要与之前相同的时间(没有索引。)

数据库视图: click here for the image

我有关于此数据库的多个小查询,例如

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

2 个答案:

答案 0 :(得分:2)

您需要为该查询提供以下索引:

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

在最后两种情况下,您可能已将该列作为PRIMARY KEY。如果是这样,请不要添加多余的INDEX

答案 1 :(得分:1)

  

我执行此操作并获得0行影响的结果   倍。这可以吗?

是的,没关系。
有DDL操作可以创建新对象而不应该输出某些东西。

  

因为当我执行查询时(在我创建索引之后)它   带我和以前一样(没有索引)

查询无法使用索引。内部优化器根据数据分布做出决策。例如,如果column_name.table_1有50个唯一值,则不使用index。

您可以在官方文档中找到更多详细信息:9.3.1 How MySQL Uses Indexes