<分区>
我试图每天选择当前记录,但时间戳给我的查询带来了问题。
SELECT * FROM `collections` WHERE rdate_collect = curdate()
在数据库中,我的记录是 2015-12-08 15:30:12
。有没有一种方法可以格式化日期,以便它只返回日期,但也返回时间,所以它只能返回当天的记录。
<分区>
我试图每天选择当前记录,但时间戳给我的查询带来了问题。
SELECT * FROM `collections` WHERE rdate_collect = curdate()
在数据库中,我的记录是 2015-12-08 15:30:12
。有没有一种方法可以格式化日期,以便它只返回日期,但也返回时间,所以它只能返回当天的记录。
最佳答案
如果您想要当前日期的所有记录,其中的值存储为 2015-12-08 15:30:12
,您可以轻松地使用 date()
在列中选择某物作为函数
其中 date(rdate_collect) = curdate()
缺点是它永远不会使用索引,即使该列已被索引,并且当您有大量数据时它会产生问题,因为查询会很慢。
因此您可以将查询格式化为
where
rdate_collect >= concat(curdate(),' ','00:00:00')
and rdate_collect <= concat(curdate(),' ','23:59:59')
这是一个活生生的例子,我有一个 login_audit
表,它有一列 last_login(datetime)
及其索引。
所以让我们一步一步看
mysql> select count(*) from login_audit ;
+----------+
| count(*) |
+----------+
| 5188680 |
+----------+
1 row in set (0.00 sec)
表中有大量记录
现在让我们使用 date() 函数并查看它在解释计划中显示的内容
mysql> explain select count(*) from login_audit where date(last_login) = curdate() ;
+----+-------------+-------------+-------+---------------+----------------+---------+------+---------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------------+-------+---------------+----------------+---------+------+---------+--------------------------+
| 1 | SIMPLE | login_audit | index | NULL | last_login_idx | 5 | NULL | 5188680 | Using where; Using index |
+----+-------------+-------------+-------+---------------+----------------+---------+------+---------+--------------------------+
从解释计划来看,mysql 可能会扫描整个表,这将是一个缓慢的查询。
现在更改查询并查看
mysql> explain select count(*) from login_audit where last_login >= concat(curdate(),' ','00:00:00') and last_login <= concat(curdate(),' ','23:59:59') ;
+----+-------------+-------------+-------+----------------+----------------+---------+------+------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------------+-------+----------------+----------------+---------+------+------+--------------------------+
| 1 | SIMPLE | login_audit | range | last_login_idx | last_login_idx | 5 | NULL | 1 | Using where; Using index |
+----+-------------+-------------+-------+----------------+----------------+---------+------+------+--------------------------+
所以是的,这次更好
这里是查询中的时间差
mysql> select count(*) from login_audit where date(last_login) = curdate() ;
+----------+
| count(*) |
+----------+
| 0 |
+----------+
1 row in set (0.92 sec)
mysql> select count(*) from login_audit where last_login >= concat(curdate(),' ','00:00:00') and last_login <= concat(curdate(),' ','23:59:59') ;
+----------+
| count(*) |
+----------+
| 0 |
+----------+
1 row in set (0.00 sec)
关于mysql - 忽略时间和小时在MySQL中获取今天的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34173757/