选择所有MySQL数据,按月计算记录,年份无法正常工作

时间:2015-12-27 18:58:11

标签: php mysql datetime

我有一个数据库表,其中包含一个IP地址列表,每个列都有一个datetime列,基本上就是这个例子:

ip_address    | date_first_viewed
192.122.42.2    2015-12-23 14:03:10
183.123.13.4    2015-12-23 02:11:10
193.311.31.6    2015-11-10 12:29:00

我正在尝试根据Month,Year选择,计数和分组数据,因此它将显示为:

(2015, 12)  2
(2015, 11)  1

这是我目前使用的查询,虽然这不会返回任何日期吗?

$sql8 = "SELECT COUNT(ip_address) as count, EXTRACT(YEAR_MONTH FROM date_first_viewed) as date
         FROM `all_website_stats`
         GROUP BY EXTRACT(YEAR_MONTH FROM date_first_viewed)";

1 个答案:

答案 0 :(得分:0)

你的SQL看起来不错。只需使用反引号转义保留字countdate即可避免问题。要以您想要的格式获取日期,您可以尝试此查询,它只是连接您想要格式化的其他字符:

SELECT CONCAT('(', YEAR(date_first_viewed), ', ', MONTH(date_first_viewed), ')') FROM table;

所以对你的例子来说:

SELECT COUNT(ip_address) as `count`, CONCAT('(', YEAR(date_first_viewed), ', ', MONTH(date_first_viewed), ')') as `date`
     FROM `all_website_stats` GROUP BY CONCAT('(', YEAR(date_first_viewed), ', ', MONTH(date_first_viewed), ')')";

应该这样做!