查找在另一个unix时间戳mysql的同一天内的所有记录

问题描述 投票:0回答:2

假设我有一个1497664242的unix时间戳,它是Saturday, June 17, 2017 1:50:42 AM

我想找到表中所有在同一天内有时间戳的记录。

我尝试设置像1494979200这样的时间戳,这是Saturday, June 17, 2017 12:00:00 AM认为我可以使用当天的一般时间并拉出当天匹配的所有记录。

我试图从特定的日期循环,找到那天匹配的所有记录然后增加1天直到今天04/12/2019

$start_date = "05/17/2017";

while ($start_date != "04/12/2019") {
    $timestamp = strtotime($start_date);
    $sql_select = "SELECT * FROM table WHERE DATE(timestamp) = DATE(FROM_UNIXTIME($timestamp))";
    $result_select = $GLOBALS['db']->query($sql_select);
    while ($row = $result_select->fetch_array()) {
        // will do stuff here
    }
    $start_date = date("m/d/Y", strtotime($start_date. "+1 day"));
}
php mysql unix-timestamp
2个回答
1
投票

如果您将时间戳转换为DATE,即2017-06-17以及数据库中的时间戳字段,那么您应该在当天获得任何行

现在我们知道列timestamp实际上被定义为VARCHAR()你必须这样做

SELECT * 
FROM table 
WHERE DATE(FROM_UNIXTIME(timestamp)) = '$start_date';

所以对于你的实际代码

$start_date = "2017-05-17";

while ($start_date != "2019-04-12") {

    $sql_select = "SELECT * 
                    FROM table 
                    WHERE DATE(FROM_UNIXTIME(timestamp)) = '$start_date'";

    $result_select = $GLOBALS['db']->query($sql_select);
    while ($row = $result_select->fetch_array()) {
        // will do stuff here
    }
    $start_date = date("Y-m-d", strtotime($start_date. "+1 day"));
}

0
投票

我不会像建议的那样在SQL查询中使用函数(DATE(FROM_UNIXTIME(timestamp))),因为这会阻止SQL在timestamp列上使用索引。

我会在php(day's begin + end)中计算两个日期时间,如下所示:

$dt       = new DateTime('@' . $timestamp); // Should take care about timezones if you need
$dt_begin = $dt->format('Y-m-d 00:00:00');
$dt_end   = $dt->format('Y-m-d 23:59:59');

如果DB中的时间戳存储为整数:

SELECT
    * 
FROM
    table 
WHERE
    timestamp BETWEEN UNIX_TIMESTAMP('$dt_begin') AND UNIX_TIMESTAMP('$dt_end')

如果DB中的时间戳存储为TIMESTAMP或DATETIME:

SELECT
    * 
FROM
    table 
WHERE
    timestamp BETWEEN '$dt_begin' AND '$dt_end'
© www.soinside.com 2019 - 2024. All rights reserved.