如何在 MySql 中的 DATETIME 字段的日期部分创建索引 [英] How does one create an index on the date part of DATETIME field in MySql

查看:58
本文介绍了如何在 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.

这篇关于如何在 MySql 中的 DATETIME 字段的日期部分创建索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆