0

我试图在过去 7 天内获得注册用户,所以我有 users 表

+-----+------------+--------------+
| ID  | USERNAME   | ADDED        |
+-----+------------+--------------+
|  1  | Vlad       | 1347386878   |
+-----+------------+--------------+
|  2  | Test       | 1347386578   |
+-----+------------+--------------+

我在sql下面试过,但输出是空的,没有错误......我需要一些从今天到7天前的东西

SELECT date(added), COUNT(id) AS num_registered 
FROM users 
WHERE added < CURDATE() 
AND added > CURDATE() - INTERVAL 7 DAYS 
GROUP BY date(added) LIMIT 1, 7

任何建议如何做到这一点?

编辑:

$mysql_query = mysql_query('SELECT added, DATE(added), COUNT(id) AS num_reg FROM users_test WHERE added < (UNIX_TIMESTAMP() - (7 * 24 * 60 * 60)) GROUP BY DATE(added) LIMIT 1, 7') or die(mysql_error());
while($row = mysql_fetch_array($mysql_query))
{
    $month = date('F', $row['added']);
    $day = date('j', $row['added']);
    $textbuilder .= '
    <li>
        <a href="#" title="'.$month.' '.$day.', '.$row['num_reg'].' registered">
            <span class="label">'.$day.'</span>
            <span class="count" style="height: 20%">('.$row['num_reg'].')</span>
        </a>
    </li>';
}

桌子:

CREATE TABLE IF NOT EXISTS `users_test` (
  `id` int(10) NOT NULL,
  `username` varchar(60) NOT NULL,
  `added` int(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `users_test` (`id`, `username`, `added`) VALUES
(1, 'Test', 1347303641),
(2, 'Test1', 1347217241),
(3, 'Test2', 1347130841),
(4, 'Test3', 1347044441);
4

3 回答 3

3

ADDED是一个 UNIX 时间戳值,所以只需执行以下操作:

SELECT
    DATE(Added), Count()
FROM
    Users
WHERE
    Added > ( UNIX_TIMESTAMP() - ( 7 * 24 * 60 * 60 ) )
GROUP BY
    DATE(Added)
LIMIT
    1, 7

请注意,这在您处理闰秒的情况下不起作用,因为它使用一天的近似定义为24*60*60,但我想您可以忍受。

于 2012-09-11T18:22:41.727 回答
0

您需要将时间戳转换为datetimeusing FROM_UNIXTIME()。由于发生了大量转换,因此使用派生表会更容易:

SELECT DATE(Added), COUNT(id) AS num_registered FROM
    (SELECT id, username, FROM_UNIXTIME(added) AS added FROM users) u
WHERE added < CURDATE()
    AND added > CURDATE() - INTERVAL 7 DAYS
GROUP BY DATE(added) LIMIT 1, 7
于 2012-09-11T18:21:37.877 回答
0
SELECT FROM_UNIXTIMESTAMP(added, ,  '%b %D, %Y'), COUNT(id) AS num_registered 
FROM users 
WHERE added > unix_timestamp() - ( 7 - 86400 )
GROUP BY FROM_UNIXTIMESTAMP(added, ,  '%b %D, %Y')
于 2012-09-11T19:17:43.630 回答