萬盛學電腦網

 萬盛學電腦網 >> 數據庫 >> mysql教程 >> MySQL獲取所有分類和每個分類的前N條記錄

MySQL獲取所有分類和每個分類的前N條記錄

本文章給大家介紹MySQL獲取所有分類和每個分類的前N條記錄,Article(Id,Category,InsertDate),現在要用SQL找出每種類型中時間最新的前N個數據組成的集合,一段不錯的代碼  代碼如下 復制代碼 SELECT A1.* 
FROM Article AS A1 
     INNER JOIN (SELECT A.Category,A.InsertDate
                 FROM Article AS A 
                      LEFT JOIN Article AS B 
                        ON A.Category = B.Category 
                           AND A.InsertDate <= B.InsertDate 
                 GROUP BY A.Category,A.InsertDate
                 HAVING COUNT(B.InsertDate) <= @N
    ) AS B1 
    ON A1.Category = B1.Category 
       AND A1.InsertDate = B1.InsertDate
ORDER BY A1.Category,A1.InsertDate DESC
copyright © 萬盛學電腦網 all rights reserved