限制 SQL 查询中每个 id 的行数 [重复]
Posted
技术标签:
【中文标题】限制 SQL 查询中每个 id 的行数 [重复]【英文标题】:Limit number of rows per id in a SQL query [duplicate] 【发布时间】:2014-03-12 17:13:52 【问题描述】:我想为每个品牌 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/
【问题讨论】:
去掉子查询。添加 order by 子句。将限制条款放在最后。 【参考方案1】:改编自另一个答案
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;
【讨论】:
【参考方案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
【讨论】:
以上是关于限制 SQL 查询中每个 id 的行数 [重复]的主要内容,如果未能解决你的问题,请参考以下文章