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
结果是:
这是一条完美的工作线。但我想优先考虑一些品牌。列出顶部。
像这样:
我用过这一行。但它没有用。
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
答案 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