在 mysql 中执行带索引和不带索引的查询

executing queries with and without indexes in mysql

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

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

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

因为当我执行我的查询时(在我创建索引之后),它花费的时间和以前一样(没有索引。)

数据库视图:

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

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

I execute this and I get the results that 0 rows has affected, both times. Is this ok?

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

Because when I execute the queries I have (after I created indexes) it takes me the same time as before (without indexes)

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

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

该查询需要这些索引:

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

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