需要按类别选择5条最新记录?

时间:2011-12-15 04:31:37

标签: mysql sql greatest-n-per-group

我需要选择每个品牌类别的五个最新产品,然后显示按类别分组的结果。

MySQL数据库看起来像;

product

product_id (pk) 
product_name 
product_etc 
product_publish_date 
brand_id (fk)

brand

brand_id (pk) 
brand_name

结果应如下所示......

brand_a product k
brand_a product a
brand_a product h
brand_a product l
brand_a product 33

brand_b product h
brand_b product z
brand_b product 9
brand_b product ddd
brand_b product a

尝试

2 个答案:

答案 0 :(得分:2)

尝试:

SELECT p.*
FROM product p1
LEFT OUTER JOIN product p2
  ON (p1.brand_id = p2.brand_id AND p1.product_id < p2.product_id)
GROUP BY p1.item_id
HAVING COUNT(*) <= 5
ORDER BY brand_id, product_publish_date;

正如比尔卡尔文所说,这与他的链接中的问题相同 - 我的回答只是对你案件的答案的改编。

答案 1 :(得分:1)

select brand_name, product_name, count(*)
from brand
INNER JOIN product on brand.brand_id = product.brand_id
order by product_publish_date
group by brand_name, product_name
having count(*) <= 5