MySQL order by field uniquness

时间:2015-06-23 11:27:06

标签: mysql laravel-5

我有一个网站,列出了来自不同供应商(数百家不同供应商)的产品。当您搜索特定产品时,我会返回一堆可以按价格等分类的产品。

我希望默认排序能够向用户展示尽可能多的独特供应商,而不使用groupby并从同一用户中删除多个产品。

因此,如果给定的搜索查询返回来自供应商a的10个产品,来自供应商b的5个产品,来自供应商C的5个产品等 - 默认排序将是显示每个产品中的一个(以任何顺序,真的) ,然后是其余的结果。

编辑:示例数据集: +----+-----------+--------------+ | id | vendor_id | product_name | +----+-----------+--------------+ | 1 | 1 | Product 1 | | 2 | 1 | Product 2 | | 3 | 1 | Product 3 | | 4 | 2 | Product 4 | | 5 | 2 | Product 5 | | 6 | 2 | Product 6 | | 7 | 3 | Product 7 | | 8 | 3 | Product 8 | | 9 | 3 | Product 9 | +----+-----------+--------------+ 期望的结果: +----+-----------+--------------+ | id | vendor_id | product_name | +----+-----------+--------------+ | 1 | 1 | Product 1 | | 4 | 2 | Product 4 | | 7 | 3 | Product 7 | | 2 | 2 | Product 2 | * any sort after initial unique results* | 3 | 2 | Product 3 | +----+-----------+--------------+ 实际上,在初始排序顺序之后进行任何排序。

1 个答案:

答案 0 :(得分:1)

您可以通过枚举每个供应商的结果然后对其进行排序来完成此操作。

select s.*
from (select s.*,
             (@rn := if(@v = vendor, @rn + 1,
                        if(@v := vendor, 1, 1)
                       )
             ) as seqnum
      from (<your query here>) s cross join
           (select @v := '', @rn := 0) params
      order by vendor
     ) s
order by (seqnum = 1) desc,
         price asc; -- or whatever you want to sort by