2011-09-10 50 views
1

基本上,我在表中有很多数据,并且它的创建日期与它有关。我想要显示表格中的所有数据,但是在输出中它需要按照日期顺序,然后在上面创建月份的标题。显示按月份分组的mysql表中的数据

数据1 数据2 数据3

DATA4 数据5

DATA6 数据7 DATA8 data9

这可能来自一个查询吗?我使用的是PHP和MySQL。

感谢

表布局将是这样的:

ID | Type | Content | User | Colour | Creation Date 

这是所有理论的时刻,但我会在今天晚些时候和明天创造它。我只需要知道是否有可能。

+0

有什么表格布局? – CodeCaster

+0

是的,但它会有助于查看您的表格定义。你能相应地编辑你的问题吗? – Lars

回答

2

我每月只需添加到查询,按日期查询,然后跟踪月份的输出相位,并插入一个新的标题,每次月份变化:

SELECT *, MONTH(thedate) AS month FROM thetable ORDER BY thedate; 

在PHP:

$lastmonth = ""; 
while ($row = mysql_fetch_assoc($queryresult)) 
{ 
    if (empty($lastmonth)) { $lastmonth = $row['month']; } 

    if ($lastmonth != $row['month']) 
    { 
    $lastmonth = $row['month']; 
    // print new month header 
    } 

    // print row 
} 
0

将MONTH列添加到您的模式并从创建日期填充它。你需要两列来做到这一点。

这听起来更像是一个报告功能,而不是事务性的东西。如果您将历史记录从OLAP数据库卸载到具有时间维度的报告星型模式中,该解决方案将非常简单。它也会减少OLAP数据集的大小。

1
$res = mysql_query('SELECT MONTHNAME(creation_date) AS month_name, data_name 
        FROM my_table ORDER BY creation_date'); 
$currentMonth = null; 
while($row = mysql_fetch_assoc($res)) { 
    if($currentMonth !== $row['month_name']) { 
     echo '<h1>'.$row['month_name'].'</h1>'; 
     $currentMonth = $row['month_name']; 
    } 
    echo '<p>'.$row['data_name'].'</p>'; 
}