【问题标题】:Limit number of rows per id in a SQL query [duplicate]限制 SQL 查询中每个 id 的行数 [重复]
【发布时间】: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 子句。将限制条款放在最后。

标签: mysql sql


【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2013-02-25
      • 2013-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      相关资源
      最近更新 更多