2

我有如下的mysql表:

STORES
store_id, rating
 10023      5
 10024      5
 10025      4
 10026      4

PRODUCTS
product_id, store_id, price
  10023         10023      5.00
  10045         10023     130.00
  10056         10023      10.00
  10057         10024      20.00
  10058         10024      12.00
  10059         10025       7.00


I need MYSQL query to retrieve records as below:
  store_id,  product_id  Price
    10023       10056    5.00
    10023       10023    10.00
    10024       10058    12.00
    10024       10057    20.00
    10025       10059     7.00

什么是正确的 SQL 查询来列出基于最高商店评级的记录,然后是最低价格和每个商店的限制 2?

4

1 回答 1

3

MySQL 没有分析函数来计算基于一组行的聚合值(例如 oracle),但您可以使用变量限制单个查询中每个字段值的行数。我试过这个,它似乎工作:

SELECT
r.store_id,
r.product_id,
r.price
FROM ( 
      SELECT *
      FROM (
            SELECT *,
            @cnt := if(@store_id = s.store_id, @cnt:= @cnt + 1, 1) AS row_count,
            @store_id:=s.store_id AS a 
            FROM stores AS s 
            LEFT JOIN (SELECT store_id AS sid, product_id, price 
                       FROM products ORDER BY store_id,price ASC) AS p 
            ON s.store_id=p.sid WHERE product_id IS NOT NULL
           ) AS b, (SELECT @store_id:='',@cnt:=0) AS c
      HAVING row_count<=2
      ORDER BY rating DESC,store_id ASC,price ASC
     ) AS r;
于 2012-09-25T10:45:39.413 回答