Get only 1 record of each category for each page in the pagination

advertisements

My table structure is as follows

id        int
name      varchar 50
catid     int

Sample data

id                     name                      catid
---------------------------------------------------------
 1                     AAA                         1
 2                     BBB                         1
 3                     CCC                         1
 4                     DDD                         2
 5                     EEE                         2
 6                     FFF                         1
 7                     GGG                         2
 8                     HHH                         2
 9                     III                         1

I want query such as it get me 1 row from each category for each page in pagination

Now for 1st Page I need data as

id                     name                      catid
---------------------------------------------------------
 1                     AAA                         1
 4                     DDD                         2

Now for 2nd Page I need data as

id                     name                      catid
---------------------------------------------------------
 2                     BBB                         1
 5                     EEE                         2

Now for 3rd Page I need data as

id                     name                      catid
---------------------------------------------------------
 3                     CCC                         1
 7                     GGG                         2

and so on.

How can I achieve this.


This worked for me (MySQL 5.1 on Linux)

SELECT id, name, catid FROM
   (SELECT id, name, catid FROM t WHERE catid=1 LIMIT 2,1) AS t1
   UNION (SELECT id, name, catid FROM t WHERE catid=2 LIMIT 2,1)
   ORDER BY catid

The 2 in the limit is the page number. Hence the output of this one is for the second page.