如何在 MySql 中的 DATETIME 字段的日期部分创建索引
如何在 DATETIME 字段的日期部分创建索引?
How do I create an index on the date part of DATETIME field?
mysql> SHOW COLUMNS FROM transactionlist;
+-------------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+------------------+------+-----+---------+----------------+
| TransactionNumber | int(10) unsigned | NO | PRI | NULL | auto_increment |
| WagerId | int(11) | YES | MUL | 0 | |
| TranNum | int(11) | YES | MUL | 0 | |
| TranDateTime | datetime | NO | | NULL | |
| Amount | double | YES | | 0 | |
| Action | smallint(6) | YES | | 0 | |
| Uid | int(11) | YES | | 1 | |
| AuthId | int(11) | YES | | 1 | |
+-------------------+------------------+------+-----+---------+----------------+
8 rows in set (0.00 sec)
TranDateTime 用于保存交易发生时的日期和时间
TranDateTime is used to save the date and time of a transaction as it happens
我的表中有超过 1,000,000 条记录和语句
My Table has over 1,000,000 records in it and the statement
SELECT * FROM transactionlist where date(TranDateTime) = '2008-08-17'
需要很长时间.
看看这篇关于的博客文章为什么 MySQL 的 DATETIME 可以而且应该避免"
推荐答案
如果我没记错的话,这将运行整个表扫描,因为您通过函数传递列.MySQL 会乖乖地为每一列运行函数,绕过索引,因为查询优化器无法真正知道函数的结果.
If I remember correctly, that will run a whole table scan because you're passing the column through a function. MySQL will obediently run the function for each and every column, bypassing the index since the query optimizer can't really know the results of the function.
我会做的是:
SELECT * FROM transactionlist
WHERE TranDateTime BETWEEN '2008-08-17' AND '2008-08-17 23:59:59.999999';
这应该会告诉你 2008-08-17 发生的一切.
That should give you everything that happened on 2008-08-17.
相关文章