如何按天选择访客数

时间:2015-12-22 15:58:16

标签: mysql sql date

我有这张桌子,我需要根据日期选择访客数量。

CREATE TABLE `visitors` (
  `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `ip` VARCHAR(32) NOT NULL,
  `browser` VARCHAR(500) NOT NULL,
  `version` VARCHAR(500) NOT NULL,
  `platform` ENUM('w','l','m') NOT NULL,
  `date` DATE NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `person` (`ip`,`date`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

我试试这个:

SELECT DATE(`date`) AS `date`, COUNT(*) AS `visitor`
FROM `visitors` WHERE (`date` >= (NOW() - INTERVAL 7 DAY))
GROUP BY `date`;

返回此内容:

date         visitor
2015-12-19    2
2015-12-22    5

但我真正想要的是:

date         visitor
2015-12-17    0        // Make 0 for the day which is not present
2015-12-17    0        // Make 0 for the day which is not present
2015-12-18    0        // Make 0 for the day which is not present
2015-12-19    2
2015-12-20    0        // Make 0 for the day which is not present
2015-12-21    0        // Make 0 for the day which is not present
2015-12-22    5

如果我尝试使用工会并获得日期,这与示例1周没有问题。但如果我需要1年,我该怎么办?

1 个答案:

答案 0 :(得分:1)

使用序列引擎。所以你可以在没有表格的情况下生成日期

https://mariadb.com/kb/en/mariadb/sequence/

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="style.css">
  <script src="script.js"></script>
</head>
<body bgcolor="#F0F0c0" onload="blinker()">
  <span style="font-weight:bold; font-size:30px;">Type of Alarm:</span>
  <div id="blink">Fire</div>
  <span style="font-weight:bold; font-size:30px;"># of Employees Clocked In:</span>
  <div id="blink">5</div>
</body>
</html>

这将在没有其他引擎的情况下工作。您只需要一个包含更多记录为天的表。向后的天数是LIMIT。

MariaDB [mysql]> SELECT date(now() - INTERVAL seq DAY) FROM seq_0_to_6;
+--------------------------------+
| date(now() - INTERVAL seq DAY) |
+--------------------------------+
| 2015-12-22                     |
| 2015-12-21                     |
| 2015-12-20                     |
| 2015-12-19                     |
| 2015-12-18                     |
| 2015-12-17                     |
| 2015-12-16                     |
+--------------------------------+
7 rows in set (0.00 sec)

请告诉你这件事。