简体   繁体   English

查询mysql:从时间戳中选择

[英]query mysql: Select from timestamp

I want to SELECT all the rows from the table that correspond to a specific date. 我想从表中选择与特定日期相对应的所有行。 I have the timestamp stored in the pattern 2010-08-18 04:43:00 . 我将时间戳记存储在模式2010-08-18 04:43:00 How can I query the table if I want to select all the rows that fall within a day's time? 如果要选择一天中的所有行,如何查询表?

One way I can think of is get the day's timestamp, convert it into Unix timestamp and then query the table. 我能想到的一种方法是获取当天的时间戳,将其转换为Unix时间戳,然后查询表。 But that sounds like a lot of work. 但这听起来像很多工作。 Is there any easier alternative? 有没有更简单的选择?

Thanks a lot in advance. 非常感谢。

SELECT *
FROM `table_name`
WHERE `date_column` LIKE '2010-08-17 %';

Or: 要么:

SELECT *
FROM `table_name`
WHERE DAY( `date_column` ) = 17
AND MONTH( `date_column` ) = 08
AND YEAR( `date_column` ) = 2010
LIMIT 0 , 30

Reference: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html 参考: http : //dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html

The approach outlined by Michael works, but is string-based and as such not as efficient as an integer-based search. Michael概述的方法行之有效,但是它是基于字符串的,因此不如基于整数的搜索有效。

I don't really see a problem in creating two UNIX timestamps, one for 00:00:00 and one for 23:59:59, and checking to see if you fall within that time. 创建两个UNIX时间戳,一个用于00:00:00,另一个用于23:59:59,并检查您是否在该时间内,我没有发现任何问题。 (Be sure to actually calculate these two separate values to make sure you account for daylight savings time). (请确保实际计算这两个单独的值,以确保考虑了夏令时)。

You can even use MySQL to get those values if you really don't want to do it yourself ( SELECT UNIX_TIMESTAMP("$Timestamp 00:00:00"), UNIX_TIMESTAMP("$Timestamp 23:59:59") ), and then use those two values. 如果您真的不想自己做,甚至可以使用MySQL获取这些值( SELECT UNIX_TIMESTAMP("$Timestamp 00:00:00"), UNIX_TIMESTAMP("$Timestamp 23:59:59") )和然后使用这两个值。

If you have a small dataset, Michael's approach above is fine. 如果您的数据集很小,那么上面的Michael方法是可以的。

Quite simply: 很简单:

SELECT *
FROM `table_name`
WHERE DATE(`date_column`) = '2010-08-17';

Note that it will only be efficient if your date_column is of type TIMESTAMP or DATETIME. 请注意,只有当您的date_column类型为TIMESTAMP或DATETIME时,它才会有效。

Edit: Since Martin raised a point related to performance, you might want to try this instead if speed is an issue (on a huge data set). 编辑:由于Martin提出了与性能有关的观点,如果速度是一个问题(在庞大的数据集上),您可能想尝试一下。 BETWEEN will make use of any available indexes. BETWEEN将使用任何可用的索引。

SELECT *
FROM `table_name`
WHERE `date_column` BETWEEN '2010-08-17 00:00:00' AND '2010-08-17 23:59:59';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM