Question

I have to get from a table containing something like

ShopId  ArticleId  Price  ArticleName

  1        1a      2.00   Fahrrad
  1        1b      3.00   Fahrrad
  1        1c      4.00   Fahrrad
  1        1d      9.99   Fahrrad
  2        2a      2.00   Fahrrad
  2        2b      3.10   Fahrrad
  2        2c      3.50   Fahrrad
  2        2d      9.99   Fahrrad

max. 3 ArticleId's per ShopId ordered by min. Price as result, e.g.:

ShopId  ArticleId  Price  ArticleName

  1        1a      2.00   Fahrrad
  1        1b      3.00   Fahrrad
  1        1c      4.00   Fahrrad
  2        2a      2.00   Fahrrad
  2        2b      3.10   Fahrrad
  2        2c      3.50   Fahrrad

Can anyone please help? So it's something like min(Price) and group by ShopId but with 3 results not 1.

Was it helpful?

Solution

Give this a bash. Don't know the name of your table so I've called it shopArticle:

select t.ShopId,t.ArticleId,t.Price,t.ArticleName
from
(
select sa.*,
            CASE sa.ShopId 
            WHEN @curShopId
            THEN @curRow := @curRow + 1 
            ELSE @curRow := 1 AND @curShopId := sa.ShopId END rank
from shopArticle sa
join (SELECT @curRow := 0, @curShopId := '') r
order by sa.ShopId,sa.Price asc
) t
where t.rank <=3;

OTHER TIPS

Using the real column-names the result is in short form: set @cr := 0, @cs := "";

select s.ShopTitle,p.*, @cr := if(@cs = p.ShopId, @cr + 1, 1) as cr, @cs := p.ShopId as cs

from affili_products2 p force index(PRIMARY) left join affili_shops s on p.ShopId=s.ShopId

where p.Keywords like "%hobby%"

group by p.ShopId, p.Price having cr <= 3 order by s.ShopTitle asc,p.Price asc

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top