2014-07-26 18 views
0

分組數據我有一個表是這樣的:SQL和PHP

Lecture_ID | Subject | Section | time_Date 

0001  | Maths | A  | .... 
0002  | Maths | B  | .... 
0003  | Maths | C  | .... 
0004  | Maths | B  | .... 

我想數據應該由段進行分組,這樣,當我echo出的數據,應該是這樣的:

Section A 
time_Date 
time_Date 

Section B 
time_Date 
time_Date 
... 

我怎樣才能實現查詢,這樣做this..All我有像

$query = 'SELECT * FROM Lecutre_info WHERE Subject="'.$_GET['subject'].'" ORDER BY Section ASC'; 
$result = mysql_query($query) or die(mysql_error()); 

while($row = mysql_fetch_array($result)) { 

print '<h1>'.$row['Section'] 
print '<br>'.$row['time_Date']; 

} 

你可以想象,我有每個記錄Section。我怎樣才能將條目分組在一起。另外我不知道有多少部分會事先提供,部分可以從任何字母開始,不一定是'A'。所以例如有可能是一個科學類與名爲X的感謝1節......

+0

'$ current_Section = ''; while($ row = mysql_fetch_array($ result)){ if($ row ['Section']!= $ current_Section){print'

'。$ row ['Section']。'

'; $ current_Section = $ row ['Section'];} print'
'。$ row ['time_Date']; }' - >創建一個變量'$ current_Section',檢查行的節是否相同,如果沒有回顯該節,並將'$ current_Section'設置爲該節。 – Sean

+0

@Fallen謝謝你 – stud91

回答

1

下面的SQL將輸出到你想要的東西:

看到小提琴:http://sqlfiddle.com/#!2/ea7f7b/21/0

select case when length(section) = 1 then 
       concat('Section ',section) 
      else substring_index(section, '/', -1) 
      end as result 
    from (select distinct section 
      from tbl 
     union all 
     select concat(section, '/', dt) 
      from tbl 
     order by 1) x 
1

通常情況下,這種類型的數據轉換在應用程序端完成。您可以將數據轉換爲這種格式。面臨的挑戰是獲取部分的多餘行,將兩種不同類型放在同一列(日期時間和字符串)中。你可以做TI爲:

select (case when time_date is null then section 
      else date_format(time_date, YOURFORMATHERE) 
     end) 
from ((select section, time_date from lecture_info li) union all 
     (select distinct section, NULL) 
    ) t 
order by section, 
     time_date is null desc, 
     time_date;