从mysql表中获取日期数据

时间:2015-03-18 09:04:57

标签: mysql mysqli

table
=====
id
firstname
lastname
registered_on int(11)
  

我想进行查询,按日期计算注册用户,这样我就可以   知道有多少用户在特定日期注册了

我的查询

 $sql = "SELECT registered_on,count(*) as cnt FROM websiteadmin_ext_jobseekers group by registered_on";
$result = $con->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
    echo date("Y-m-d",$row["registered_on"]);
        echo "count: " . $row["cnt"]. "<br> ";
    }
} else {
    echo "0 results";
}

和结果

2015-03-14count: 1
2015-03-14count: 1
2015-03-14count: 1
2015-03-14count: 1
2015-03-14count: 1
2015-03-14count: 1
2015-03-14count: 1
2015-03-14count: 1
2015-03-14count: 1
2015-03-14count: 1
2015-03-14count: 1

我的问题是

  

数据未按日期分组显示

2 个答案:

答案 0 :(得分:0)

试试这个:

$query = "SELECT `registered_on`, COUNT(*) AS `count` FROM `websiteadmin_ext_jobseekers` GROUP BY DATE(`registered_on`)";

答案 1 :(得分:0)

日期列的数据类型为

registered_on int(11)

在你的PHP代码中,它看起来像unix时间戳

 echo date("Y-m-d",$row["registered_on"]);

因此您需要将查询修改为

SELECT 
registered_on,
count(*) as cnt 
FROM websiteadmin_ext_jobseekers 
group by date(FROM_UNIXTIME(registered_on)) 

更好的是像eggyal指出的那样

SELECT 
date(FROM_UNIXTIME(registered_on))  as registered_on_date,
count(*) as cnt 
FROM websiteadmin_ext_jobseekers 
group by registered_on_date ;

使用上面的查询,在PHP中使用索引为registered_on_date,无需转换为date只需使用

echo $row["registered_on_date"];