且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为每个类别选择N条记录,并按X排序

更新时间:2023-01-28 19:30:48

MySQL 不支持分析功能(ROW_NUMBER,RANK,DENSE_RANK,NTILE ...),但是您可以模拟该功能带有变量.

MySQL doesn't support analytic functions (ROW_NUMBER, RANK, DENSE_RANK, NTILE...), but you can emulate the functionality with variables.

如果您要 N 最近的博客文章:

If you want the N most recent blog posts:

SELECT x.id,
       x.title,
       x.description,
       x.cat,
       x.filename,
       x.date
  FROM (SELECT bp.id,
               bp.title,
               bp.description,
               bp.cat,
               bp.filename,
               bp.date,
               CASE 
                 WHEN bp.cat = @category THEN @rownum := @rownum + 1
                 ELSE @rownum := 1
               END AS rank,
               @category := bp.cat
          FROM BLOG_POSTS bp
          JOIN (SELECT @rownum := 0, @category := NULL) r
      ORDER BY bp.cat, bp.date DESC) x
 WHERE x.rank <= N

如果您希望等级1成为最早的博客文章,请将ORDER BY更改为:

If you want rank of 1 to be the earliest blog post, change the ORDER BY to:

ORDER BY bp.cat, bp.date