tags:

views:

29

answers:

1

This may be a tough one for you all, if it is even possible in mysql.
I have a table that stores id, catid, product_name
What i would like to do is select 3 records for each catid then display the result with each 3 sets of records first.
So if i have a catid of 4, 7 then I would like to display 3 results for (4) then 3 results for (7).

Any help is greatly appreciated. Thanks.

A: 

Use:

SELECT x.id,
       x.catid,
       x.product_name
  FROM (SELECT t.id,
               t.catid,
               t.product_name,
               CASE 
                 WHEN @catid = t.catid THEN @rownum := @rownum + 1
                 ELSE @rownum := 1
               END AS rank,
               @catid := t.catid
          FROM YOUR_TABLE t
          JOIN (SELECT @rownum := 0, @catid := -1) r
      ORDER BY t.catid, t.product_name) x
WHERE x.rank <= 3

Mind that I've seen weird behavior from MyISAM tables -- InnoDB tables are more consistent.

OMG Ponies
Thanks very much. It is very close but it is showing only 8 result even though there are many records within each categories. It shows the catid(1) perfectly but for catid(2), catid(3) and so on, it only shows one record for each. I have to change x.rank <= 3 to 2 since it was showing 4 results. I am using MyISAM
tomb
@tomb: As my comment states, MyISAM tends not to give consistent results. MySQL has no native syntax for what you want.
OMG Ponies