I've tables: 1.star_article(article_id``itemid``title`): Stores Submitted Articles 2.star_item(`itemid``cat_id``title`): Stores different items under several cat_id Brief:Under one Category(cat_id = "10") there are 3 Items(2,21,23) Under Every itemid there are several articles are submitted e.g:Under itemid=2 article_id=24, article_id=25, article_id=29 are submitted. I've retrieved latest submitted articles of every itemids under 1 cat_id: With this query: SELECT waa.article_id,waa.title,star_item.itemid FROM star_article as waa LEFT JOIN star_item ON waa.itemid=star_item.itemid WHERE waa.article_id IN(SELECT MAX(article_id) FROM star_article GROUP BY itemid) AND star_item.itemid IN(Select itemid from star_item WHERE cat_id=10)order by waa.article_id desc Now, I want to get top 5 articles of every itemid like this: article_id title itemid Latest article Article Title 21 ('coz 21 had submitted last) Latest article Article Title 23 ('coz 23 had submitted b4 21) Latest article Article Title 2 ('coz 2 had submitted b4 23) 2nd Latest article -do- 21 ('coz 21 had submitted last) 2nd Latest article -do- 23 ('coz 23 had submitted b4 21) 2nd Latest article -do- 2 ('coz 2 had submitted b4 23) and so on. . . Please Help me write this complex query. . . Thanks in advance
------------------------please check the query for you problem. its written in TSQL may be it help you I have Taken temp table and just change few columns name. it will work for you just need to change the column name and table name in query. select * from #star_item inner join ( --------------this quesry has the logic of top 5 articels from the table---------------- Select * From #star_article t1 Where (6-1) > (Select Count(Distinct(t2.aid)) From #star_article t2 Where t2.aid > t1.aid and t2.ITID=t1.itid ) )A on itid=iti