2012-11-15 59 views
0

我有一個MySQL表:Mysql的化合物進入

+----+----------------------------+ 
| id | name | datetime   | 
+----+----------------------------+ 
| 1 | Qwe | 2012-11-20 08:00:00 | 
| 2 | Foo | 2012-11-20 05:00:00 | 
| 3 | Bar | 2013-01-01 08:00:00 | 
+----+----------------------------+ 

如何從數據庫與MySQL得到這樣的:

date 
id - time - name 

2012-11-20 
2 - Foo - 05:00 
1 - Qwe - 08:00 

2013-01-01 
3 - Bar - 08:00 
+0

怎麼弄它從數據庫與PHP? – user1802209

+1

你需要一個字符串嗎?或不?或者您需要按日期分組? – Reflective

+0

@反射是的,我需要按日期對它進行分組,如上例所示。 – user1802209

回答

3

一種方法

$sql = "SELECT id, name, 
     DATE_FORMAT(`datetimecol`, '%Y-%m-%d') mydate, 
     DATE_FORMAT(`datetimecol`, '%H:%i') mytime 
     FROM yourtabe"; 
$result = mysql_query($sql); 
$dataarr = array(); 
if($result && mysql_num_row($result) > 0) { 
    while($row2 = mysql_fetch_assoc($result)) { 
    $dataarr[$row2['mydate']][] = $row2;  
    } 
} 

if(count($dataarr) > 0) 
    foreach($dataarr as $key => $data) { 
     echo '<h3>'.$key.'</h3>'; 
     foreach($data as $row) { 
     echo '<p>'. $row['id'].', '.$row['name'].', '.$row['mytime'].'</p>'; 
     } 
    } 
} 
0

我尼特知道究竟你需要做的,但可以給你如何讓你的初始排序的基本的例子:

select date(datetime), id, name, TIME_FORMAT(datetime, '%H:%i') from tmp order by datetime