简体   繁体   中英

MySQL Output by Category with Pagination

I have a database:

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...

etc...

I want to output the whole table, but group everything into categories. So the output would look like:

<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>

etc...

What's the best way to go about doing this? My first try at this, I ran through each entry, comparing it's category to the last entry. It worked, however, that method proved to be complex, especially when it came time to try to implement pagination. My next thought was to have some sort of nested foreach loop, the outer for the category, the inner for the item. Could that work somehow? And would it work when implementing pagination? Thanks for your help!

Using a GROUP BY and WITH ROLLUP modifier may help separate the categories:

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

This will output something like:

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

Now you can see that if title is empty you've reached the end of the category. You can also see how many pages are in a particular category for pagination.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM