ORDER BY基于行的最大行数

时间:2015-04-14 17:57:12

标签: mysql sql

表格字段: shop_id,product_id

  1. 我想要一份包含特定产品的商店清单(应该至少有一种产品)
  2. 结果应根据具有最大指定产品数量的商店进行分类
  3. 我可以为第一部分编写sql查询,但是列表没有按照匹配最大产品数量的商店进行排序

    SELECT 
        shop_id,
        product_id
    FROM
        products_table
    WHERE
        product_id IN (1,2,3)
    ORDER BY ???
    

    是否有最佳解决方案?

2 个答案:

答案 0 :(得分:3)

加入子查询,获取每个商店的计数,然后按顺序排序。

SELECT a.shop_id, a.product_id
FROM products_table AS a
JOIN (SELECT shop_id, COUNT(*) AS product_count
      FROM products_table
      WHERE product_id in (1, 2, 3)
      GROUP BY shop_id) AS b
ON a.shop_id = b.shop_id
WHERE product_id IN (1, 2, 3)
ORDER BY b.product_count DESC

答案 1 :(得分:0)

这样的查询将避免重复product_id列表:

with sp as (
    select shop_id, product_id
    from products_table
    where product_id IN (1,2,3)
)
select
    shop_id, product_id,
    (select count(*) from sp as sp2 where sp2.shop_id = sp.shop_id) as shop_count
from sp
order by shop_count desc

但现在我看到你正在使用MySQL,所以尽管它可以扩展,但它不会为你工作:

select
    shop_id, product_id,
    (
        select count(*) from products_table as p2
        where product_id in (1,2,3) and p2.shop_id = p.shop_id
    ) as shop_count
from products_table as p
where product_id in (1,2,3)
order by shop_count desc;

它本质上是相同的查询,但隐含了连接。我认为MySQL并不总能非常有效地处理相关查询。我认为Barbar的答案的味道是你必须使用的,除非你创建一个临时表镜像" sp"上方。

作为旁注,我学习语言,我觉得我选择调用我的计算专栏" shop_count"而其他Barmar则选择" product_count。尽管我们实际上是在计算产品,但我还是将商店作为我关注的焦点。给我" shop_count"表示"计算每个商店"而Barbar可能会将他描述为"产品数量"。我决不认为一种方法更有效或更自然。看到人们可以采取的不同观点,这对我来说非常有吸引力。

相关问题