我想限制每个brand_id的10个产品的结果。这是我的查询的样子:
SELECT
products.id, products.brand_id
FROM products
JOIN (
select id, brand_id
from products limit 10)
pinner ON products.id = pinner.id
WHERE pinner.brand_id IN ('1', '2','3') ;
这显然不起作用。有什么建议吗?
修改 这篇文章帮助我解决了这个问题:http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/
答案 0 :(得分:2)
试试这个
SET @rownum =0;
SELECT id,brand_id FROM
(
SELECT
products.id, products.brand_id, @rownum := @rownum + 1 AS rank
FROM products
JOIN (
SELECT id, brand_id
from products limit 10)
pinner ON products.id = pinner.id
WHERE pinner.brand_id IN ('1', '2','3')
) AS T
Where rank < 10
答案 1 :(得分:2)
改编另一个答案
set @brand_id= '';
set @num = 0;
select
products.id, products.brand_id,
@num := if(@brand_id= brand_id, @num + 1, 1) as dummy_1,
@brand_id:= brand_id as dummy_2,
@num as row_number
from products
where brand_id IN ('1', '2','3')
group by
brand_id,
row_number
having row_number <= 10;