MySQL - How to apply LIMIT to GROUP?

2019-07-31 18:37发布

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.

2条回答
甜甜的少女心
2楼-- · 2019-07-31 19:11

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
查看更多
Animai°情兽
3楼-- · 2019-07-31 19:30

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
查看更多
登录 后发表回答