2011-12-15 56 views
1

我需要選擇每個品牌類別的五種最新產品,然後顯示按類別分組的結果。需要按類別選擇5個最新記錄?

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 

試圖與

+0

SELECT * FROM產品 GROUP BY brand_id ORDER BY product_publish_date LIMIT 5 – Adrian 2011-12-15 04:39:41

回答

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; 

比爾karwin說,這是同樣的問題,因爲在他的鏈接 - 我的回答僅僅是回答你的情況的適應。

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