Mysql 在结果中按计数排序

Mysql 在结果中按计数排序,mysql,Mysql,我在计算如何按结果计数排序结果时遇到问题。我想做的是按产品出现的数量排序结果: 数据: 预期成果: product 3 5 4 结果还需要排除当前产品,因此我使用子查询解决了这个问题: SELECT Product,userID FROM ProductTable WHERE userID IN(SELECT userID FROM productViewed WHERE Product="4817") AND Product<>"4817" 我尝试过使用Group By和Ord

我在计算如何按结果计数排序结果时遇到问题。我想做的是按产品出现的数量排序结果:

数据:

预期成果:

product
3
5
4
结果还需要排除当前产品,因此我使用子查询解决了这个问题:

SELECT Product,userID FROM ProductTable WHERE userID IN(SELECT userID FROM productViewed WHERE Product="4817") AND Product<>"4817"
我尝试过使用Group By和Order By的Countproduct,但这似乎不起作用

这是实现这一目标的正确方法吗

谢谢

里克

试试下面的方法:

SELECT 
product FROM 
(SELECT 
product,COUNT(userid) AS cnt 
FROM producttable 
GROUP BY product) as a 
WHERE product<>'excluding product' 
ORDER BY cnt DESC;

请检查此SQL小提琴以获取您的答案

查询:

select product from ProductTable
group by product order by count(userId) desc;
在此查询中,添加子查询以根据需求排除产品

希望这有助于:

select product from ProductTable
group by product order by count(userId) desc;