1. 程式人生 > >mysql 取每個分類下的N條記錄

mysql 取每個分類下的N條記錄

第一種方式
SELECT 
    *
FROM
    tablename AS a
WHERE
    (SELECT 
            COUNT(*)
        FROM
            tablename AS b
        WHERE
            b.分類id = a.分類id AND b.id >= a.id) <= 5
ORDER BY a.分類id ASC , a.id DESC

第二種方式
SELECT 
    *
FROM
    tablename AS a
WHERE
    (SELECT 
            COUNT(*)
        FROM
            tablename AS b
        WHERE
            b.type = a.type AND b.id >= a.id) <= 5
ORDER BY a.type ASC , a.id DESC