MYSQL品牌按产品数量排序,但是

时间:2014-07-27 11:19:51

标签: mysql sql select count distinct

我有两张桌子。像这样;


Products table

id | brand | bla bla bla

Priority table

id | brand

我正在列出SELECT DISTINCT品牌FROM产品表BY ORDERING产品COUNT这样;

SELECT DISTINCT brand as bra, (SELECT COUNT(id) FROM Products WHERE brand = bra) as cnt FROM Products ORDER BY cnt DESC

结果是:

  1. A Brand(65产品)
  2. B Brand(43产品)
  3. C Brand(23产品)
  4. D Brand(17产品)
  5. 这是一条完美的工作线。但我想优先考虑一些品牌。列出顶部。

    像这样:

    1. S Brand(22产品)
    2. X Brand(4个产品)
    3. A Brand(65产品)
    4. B Brand(43产品)
    5. C Brand(23产品)
    6. D Brand(17产品)
    7. 我用过这一行。但它没有用。

      SELECT DISTINCT brand as bra, (SELECT COUNT(id) FROM Products WHERE brand = bra) as cnt, , (SELECT brand FROM Priority) as prior FROM Products ORDER BY prior ASC,cnt DESC
      

      什么是真行?感谢...

      --- --- EDIT 完全答案是:

      SELECT p.brand as bra, count(p.id) as cnt
      FROM products p
      GROUP BY bra
      ORDER BY bra IN (SELECT pri.brand FROM priority pri ORDER BY pri.brand ASC) DESC, mark ASC
      

2 个答案:

答案 0 :(得分:1)

您的第一个查询更清楚地写为:

SELECT b.brand as bra, count(p.id) as cnt
FROM bra b left outer join
     Products p
     on b.brand = p.brand
GROUP BY b.bra
ORDER BY cnt DESC;

仅在您担心不匹配的记录时才需要left outer join。如果这不是问题,编写查询的更简单方法是:

SELECT p.brand as bra, count(p.id) as cnt
FROM Products p
GROUP BY p.bra
ORDER BY cnt DESC;

如果您想按优先顺序排序,只需加入即可。这可能是您想要的:

SELECT p.brand as bra, count(p.id) as cnt
FROM bra b left outer join
     Products p
     on b.brand = p.brand left outer join
     Priority pr
     on b.brand = pr.brand
GROUP BY b.bra
ORDER BY pr.brand is not null desc, cnt DESC;

这将首先将品牌放在优先级表中。

答案 1 :(得分:1)

使用此:

ORDER BY bra IN (SELECT brand FROM Priority) DESC, cnt DESC