【发布时间】:2015-11-28 08:46:12
【问题描述】:
我尝试优化这个查询:
select id_store from receipt where receiptDate between '20151109' and '20151116'
我使用命令EXPLAIN 执行此查询。似乎没有使用任何密钥。不使用receiptDate 的索引。怎么了 ?
这是表receipt的结构:
CREATE TABLE receipt (
id_store tinyint(3) unsigned NOT NULL default '0',
id_receipt int(7) unsigned NOT NULL default '0',
id_product smallint(6) unsigned NOT NULL default '0',
receiptDate char(8) NOT NULL default '',
qty float NOT NULL default '0',
turnover float NOT NULL default '0',
PRIMARY KEY (id_store,id_receipt,id_product,receiptDate),
KEY NDX_1 (receiptDate),
) ENGINE=MEMORY;
这是命令EXPLAIN 的结果:
+----+-------------+---------------------+--------+-----------------------------------------------------------+---------------------------------+---------+--------------------------------------+------+---------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------------------+--------+-----------------------------------------------------------+---------------------------------+---------+--------------------------------------+------+---------------------------------+
| 1 | SIMPLE | receipt | ALL |NDX_1 | | | |24789225| Using where |
+----+-------------+---------------------+--------+-----------------------------------------------------------+---------------------------------+---------+--------------------------------------+------+---------------------------------+
receipt 表包含 24.789.225 行,平均每天有 15.000 行(receiptDate)。
我执行以下查询并获得 120.295 行:
select count(*) from receipt where receiptDate between '20151109' and '20151116'
提前感谢您的帮助。
【问题讨论】:
-
您应该发布表结构并解释结果。我们看不到您的屏幕
-
您还可以发布数据分布
select COUNT(),receiptDate from receipt group by receiptDate并运行相同的查询,但使用您的 where 条件。使用两个结果编辑您的问题,我怀疑基数不佳。 -
您的查询返回表中的所有行,因此使用索引没有意义。当您需要一小部分数据时,索引很有用。
-
在INT中转换receiptDate
-
米海,谢谢,但是如果您阅读我的帖子,查询返回 120.295 行。该表包含 24.789.225 行。
标签: mysql optimization range