我需要选择每个品牌类别的五个最新产品,然后显示按类别分组的结果。
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 :(得分: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