简体   繁体   中英

MySQL - How to apply LIMIT to GROUP?

I create a kind of a blog engine, where posts are categorized into month-year categories, based on timestamp. I use the following query:

SELECT MONTHNAME( post_time ) AS
month , YEAR( post_time ) AS year
FROM blog_posts
GROUP BY year,
month
ORDER BY post_time DESC
LIMIT 0 , 10

which returns me the latest ten post categories like this:

December 2010
November 2010
...
etc

My question is how do I create a query to fetch older/newer categories?

If I had a column like *category_id* I'd be able to easily use it with LIMIT, but as month and year is all I have I'm stuck.

Help greatly appreciated, this one's a riddle for me.

My question is how do I create a query to fetch older/newer categories?

This query:

SELECT  MONTHNAME(post_time) AS month, YEAR(post_time) AS year
FROM    blog_posts
GROUP BY
        year, month
ORDER BY
        post_time DESC
LIMIT 0, 10

groups by months and years and orders by time of the random post within each month and year.

Since the order of these random posts correspond to that of months and years, your categories will go out in correct order (recent to early).

Update:

To show 10 categories before June 2010 :

SELECT  MONTHNAME(post_time) AS month, YEAR(post_time) AS year
FROM    blog_posts
WHERE   post_time < '2010-06-01'
GROUP BY
        year, month
ORDER BY
        post_time DESC
LIMIT 0, 10

If blog_posts have category_id

SELECT MONTHNAME( post_time ) AS
month , YEAR( post_time ) AS year
FROM blog_posts
GROUP BY year,
month
ORDER BY category_id DESC
LIMIT 0 , 10

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