views:

15

answers:

1

I have a product table like this:

Product name , Affiliate ID , ProductCode
a, 1, 1
b, 1, 2
c, 1, 3
d, 1, 5
e, 1, 7
f, 2, 4
g, 2, 6

I want to return first four products from each Affiliate ID. The 'ProductCode' column signifies the order in which the products were added, so can I use this column to sort my results. But I don't know how to return the first four results from each Affiliate ID? If I use the 'group' function it returns only one row of each affiliate ID.

+1  A: 

Look to the example in this link:

Within-group quotas (Top N per group)

it is exactly that you need.

 SELECT AffiliateId, ProductCode 
 FROM ( 
    SELECT 
      AffiliateId, ProductCode, 
      IF( @prev <> ID  @rownum := 1, @rownum := @rownum+1 ) AS rank, 
      @prev := ID 
    FROM your table 
 JOIN (SELECT @rownum := NULL, @prev := 0) AS r 
 ORDER BY AffiliateId, ProductCode 
 ) AS tmp 
 WHERE tmp.rank <= 4
 ORDER BY AffiliateId, ProductCode; 
Michael Pakhantsov
Thanks - yes that looks like what I need. However I'm getting the following error: Query : SELECT `name`, productId, image, affiliate_id, productCode FROM ( SELECT `name`, productId, image, affiliate_id,...Error Code : 1064You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@rownum := 1, @rownum := @rownum+1 ) AS rank, @prev := ID FROM `Cu' at line 5Execution Time : 00:00:00:000Transfer Time : 00:00:00:000Total Time : 00:00:00:000
Joe Smalley
@Joe What is your mysql version?
Michael Pakhantsov
MySQL Version 5.0.91
Joe Smalley
My updated query: SELECT tmp.`name`, tmp.productId, tmp.image, tmp.affiliate_id, tmp.productCode FROM ( SELECT `name`, productId, image, affiliate_id, productCode, IF( @PREV <> ID @rownum := 1, @rownum := @rownum+1 ) AS rank, @PREV := affiliate_id FROM `CubeCart_inventory` t JOIN (SELECT @rownum := NULL, @PREV := 0) AS r ORDER BY t.affiliate_id, t.productCode ) AS tmp WHERE tmp.rank <= 4 ORDER BY affiliate_id, productCode;
Joe Smalley
also try add before query SET @rownum := NULL, @prev := NULL;
Michael Pakhantsov
Fixed it - there was a comma missing in that line, and I needed to substitute ID for affiliate_id - working now, thanks so much!!
Joe Smalley