我试图为每个品牌返回有限数量的产品。表格是
品牌:
id
,name
产品:
id
,brand_id
,name
我想要实现的是一个查询,它会为每个品牌输出brands.name和products_name 10次。
我已尝试加入这两个表,但在应用限制时,我无法看到下一步。这是可能的还是我必须首先选择进行品牌查询,然后再次查询这个处理器更密集的问题?
答案 0 :(得分:2)
通过以下查询从第二个表中获取每个产品10条记录:
SELECT *
FROM(
SELECT id, brand_id, name, @n := IF(@r = brand_id, @n + 1, 1) AS rownum,
@r := brand_id
FROM product, (SELECT @r := 0, @n := 0) a
ORDER BY brand_id, id
) a
WHERE a.rownum <= 10;
并join
与brand
表格,例如:
SELECT *
FROM brand b
JOIN (SELECT *
FROM(
SELECT id, brand_id, name, @n := IF(@r = brand_id, @n + 1, 1) AS rownum,
@r := brand_id
FROM product, (SELECT @r := 0, @n := 0) a
ORDER BY brand_id, id
) a
WHERE a.rownum <= 10
) p on b.id = p.brand_id;
这里是 SQL Fiddle 。