2011-09-10 49 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>'; 
}