2014-06-13 86 views
0

分類我有一個數據庫:MySQL的輸出與分頁

category | title | other fields... 
cat1  | title1 | other fields... 
cat1  | title2 | other fields... 
cat1  | title3 | other fields... 
cat1  | title4 | other fields... 
cat2  | title5 | other fields... 
cat2  | title6 | other fields... 
cat2  | title7 | other fields... 
cat3  | title8 | other fields... 

等等

我要輸出整個表,但一切都組進行分類。因此,輸出將類似於:

<div class="category"> 
    <h1>cat1</h1> 
    <div class="item">title1</div> 
    <div class="item">title2</div> 
    <div class="item">title3</div> 
    <div class="item">title4</div> 
</div> 
<div class="category"> 
    <h1>cat2</h1> 
    <div class="item">title5</div> 
    <div class="item">title6</div> 
    <div class="item">title7</div> 
</div> 
<div class="category"> 
    <h1>cat3</h1> 
    <div class="item">title8</div> 
</div> 

等等

什麼是去這樣做的最佳方式?我的第一個嘗試,我跑過每個條目,將它的類別與最後一個條目進行比較。然而,它的工作證明這種方法非常複雜,特別是當試圖實施分頁時。我的下一個想法是有一些嵌套的foreach循環,外部的類別,內部的項目。莫名其妙地工作嗎?並且在執行分頁時會起作用嗎?謝謝你的幫助!

+0

只需使用一個簡單的PHP循環來安排的結果隨你便。 – Strawberry

回答

0

使用GROUP BYWITH ROLLUP調節劑可以幫助分開的類別:

SELECT category, title, count(*) 
FROM pages 
GROUP BY category,title WITH ROLLUP; 

這將輸出類似:

category | title | other fields... | count 
cat1  | title1 | other fields... | 1 
cat1  | title2 | other fields... | 1 
cat1  | title3 | other fields... | 1 
cat1  | title4 | other fields... | 1 
cat1  | NULL | last other fields... | 4 
cat2  | title5 | other fields... | 1 
cat2  | title6 | other fields... | 1 
cat2  | title7 | other fields... | 1 
cat2  | NULL | last other fields... | 3 
cat3  | title8 | other fields... 
cat3  | NULL | last other fields... | 1 
NULL  | NULL | last other fields... | 8 

現在你可以看到,如果標題是空的,你已經到達類別的結尾。您還可以查看特定類別中有多少頁面用於分頁。