場景:
一個文章表,存放有關PHP的文章,和MySQL的文章,想從這些文章類別各自提取N條記錄出來。
測試表語句:
CREATETABLEarticle(
idINTUNSIGNEDNOTNULLAUTO_INCREMENTPRIMARYKEY,
cateVARCHAR(20),
titleVARCHAR(20)
);
INSERTINTOarticle(cate,title)VALUES
(php,php文章1),
(mysql,mysql文章1),
(php,php文章2),
(mysql,mysql文章2),
(php,php文章3),
(mysql,mysql文章3),
(php,php文章4),
(mysql,mysql文章4),
(php,php文章5),
(mysql,mysql文章5),
(php,php文章6),
(mysql,mysql文章6),
(php,php文章7),
(mysql,mysql文章7),
(php,php文章8),
(mysql,mysql文章8);
方案一:
SELECTa.id,a.title,a.cate
FROMarticleASaLEFTJOINarticleASbONa.cate=b.cateANDa.id<b.id
GROUPBYa.id,a.title,a.cate
HAVINGCOUNT(b.id)<5
ORDERBYa.idDESC;
方案二:
SELECT*FROMarticleASa
WHERE5>(SELECTCOUNT(*)FROMarticleWHEREcate=a.cateANDid>a.id)
ORDERBYa.idDESC;