2013-03-11 86 views
-1

我在MySQL表如何按日期在Php或MySQL中对数据进行分组?

comment_id comment_by_user comment_date    comment_body 
    1244   david_sam  2013-02-27 15:46:53   xyz 
    1245   raymond_davis 2013-02-27 13:46:53   xyz 
    1246   jam_jam   2013-02-14 18:46:53   xyz 

我想将此数据作为

2013-02-27 ------------------------------------- 
1244  david_sam  15:46  xyz  
1245  raymond_davis 13:46  xyz 
2013-02-14 ------------------------------------- 
1246  jam_jam   18:46  xyz 

我如何能做到这一点,其中SQL查询和PHP方法?

+1

[你尝试过什么?](http://whathaveyoutried.com) – 2013-03-11 10:53:21

+0

为了让生活为自己的SQL查询应该只在YYYY-MM-DD的格式返回日期更加容易。如果你也回来了,你只需要在稍后阶段过滤它。 – CathalMF 2013-03-11 10:58:22

+2

MySQL无法产生您要求的输出。相反,您应该选择'DATE(comment_date)作为comment_date'以及其他列。在你的PHP输出中,你必须在每个循环迭代中测试日期是否发生变化,如果有,输出一个新的标题。 – 2013-03-11 10:58:41

回答

2

您只需选择所需的所有列

select comment_id, comment_by_user, 
     date(comment_date), time(comment_date), comment_body 
from comments 
order by comment_date desc, comment_id 

然后输出行,当日期改变

$current_date = ''; 
while (list($id, $user, $date, $time, $body) = $sth->fetch(PDO::FETCH_NUM)) { 
    if ($date != $current_date) { 
     echo "$date ----\n"; 
     $current_date = $date; 
    } 

    echo "$id $user $time $body\n"; 
} 
0

试试这个插入附加行..

SELECT * FROM `table_name` ORDER BY `comment_date` DESC 

而你的php代码应该像这样..

$date = ''; 
foreach($records as $record) 
{ 
    if($date != date('Y-m-d'), strtotime($record->comment_date)) 
    { 
     // print "2013-02-14 -------------------------------------"; 
     $date = date('Y-m-d'), strtotime($record->comment_date); 
    } 

    // print "1246  jam_jam   18:46  xyz"; 
} 
相关问题