我们有一个非常大的数据库,并且用非常简单的术语提出问题,我无法决定是否应该在日期字段上添加索引。
我的查询是:我是否应该在表 A 的日期字段上添加索引,该表非常大且日期(格式:2013-02-26 18:52:23)。以下是我的查询:
SELECT As.id
FROM As INNER JOIN A_items ON A_items.A_id = As.id AND A_items.type IN ('BilledItem', 'CustomerItem')
WHERE (As.A_date BETWEEN '2013-01-15 18:52:23' AND '2013-01-30 18:52:23') AND A_items.category_id in ('20219') and A_items.product_id IN ('ACCDYHGYUDZNY7FZ')
现在,当我对此使用解释时,它给了我以下结果:-
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: A_items
type: ref
possible_keys: index_A_items_on_A_id,index_A_items_on_product_id,i_type_parent_id_item_type
key: index_A_items_on_product_id
key_len: 258
ref: const
rows: 221122
Extra: Using where
*************************** 2. row ***************************
id: 1
select_type: SIMPLE
table: As
type: eq_ref
possible_keys: PRIMARY
key: PRIMARY
key_len: 8
ref: database.A_items.A_id
rows: 1
Extra: Using where
2 rows in set (0.00 sec)
但是,当我从查询中删除 A_items.product_id IN ('ACCDYHGYUDZNY7FZ') 并运行以下命令时:-
explain
SELECT As.id
FROM As INNER JOIN A_items ON A_items.A_id = As.id AND A_items.type IN ('BilledItem', 'CustomerItem')
WHERE (As.A_date BETWEEN '2013-01-15' AND '2013-01-30') AND A_items.category_id in ('2005')
我得到:-
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: As
type: ALL
possible_keys: PRIMARY
key: NULL
key_len: NULL
ref: NULL
rows: 15427520 <--Notice this big number
Extra: Using where
*************************** 2. row ***************************
id: 1
select_type: SIMPLE
table: A_items
type: ref
possible_keys: index_A_items_on_A_id,i_type_parent_id_item_type
key: index_A_items_on_A_id
key_len: 8
ref: database.As.id
rows: 1
Extra: Using where
2 rows in set (0.00 sec)
我的问题是为什么第一个查询中没有显示这么多行以及如何决定是否在日期字段上添加索引???