比如有文章表 Article(Id
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
@N 就是你要取多少條
下面是我用到了一個(gè)產(chǎn)品分類表中,superId是大分類,prcid是產(chǎn)品分類。能用SQL完成的功能就要盡量用SQL語(yǔ)句來(lái)完成,這既簡(jiǎn)潔又高效。
SELECT
A1.*
FROM
prcKx AS A1
INNER JOIN (
SELECT
A.superId,
A.prcid
FROM
prcKx AS A
LEFT JOIN prcKx AS B ON A.superId = B.superId
AND A.prcid <= B.prcid
GROUP BY
A.superId,
A.prcid
HAVING
COUNT(B.prcid) <= 7
) AS B1 ON A1.superId = B1.superId
AND A1.prcid = B1.prcid
ORDER BY
superId,
prcid
需求是這樣的(CSDN上的一個(gè)問(wèn)題):mysql中有個(gè)表:article(字段:id,type,date),type有1-10,10種類型?,F(xiàn)在要用SQL找出每種類型中時(shí)間最新的前N個(gè)數(shù)據(jù)組成的集合。
這個(gè)問(wèn)題應(yīng)該有很多方法可以實(shí)現(xiàn),下面就來(lái)說(shuō)說(shuō)在網(wǎng)上看到的一位高手的實(shí)現(xiàn)(用一條SQL語(yǔ)句實(shí)現(xiàn)的,個(gè)人感覺(jué)非常好,所以拿來(lái)和大家分享):
select a1.* from article a1
inner join
(select a.type,a.date from article a left join article b
on a.type=b.type and a.date<=b.date
group by a.type,a.date
having count(b.date)<=2
)b1
on a1.type=b1.type and a1.date=b1.date
order by a1.type,a1.date desc
注:上面sql語(yǔ)句中的2代表的就是前面提到的N。
以上所述就是本文的全部?jī)?nèi)容了,希望大家能夠喜歡。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注