我在尝试了解如何构建此查询时遇到问题。
我的数据方案:
id category name userid
1 sports football 1
2 cars ferrari 1
3 sports basketball 1
4 film Matrix 9
5 film Fauno 9
6 sports Surf 3
如您所见,类别 即使对于相同的用户 ID 也可以重复,因为 name 字段不同。所以我的想法是获取一组用户的类别和该组中每个类别的用户数量。
假设我有一组用户 set_of_user = (1,9,3),如果我运行查询
SELECT something FROM category_table WHERE userid IN set_of_user SOME CONDITION HERE
正确的结果应该是:
category: sports
users: 2
category: cars
users: 1
category: film
users: 1
我最好的镜头是:
SELECT userid, category, COUNT(userid) as users from interests WHERE `userid` in ' . $norm_info_ids . ' GROUP BY category
但是结果不好,我该如何解决呢?
最佳答案
我认为这就是您使用 COUNT
和 DISTINCT
以及 GROUP BY
寻找的内容:
select category, count(distinct userid)
from interests
where userid in (1,3,9)
group by category
导致:
CATEGORY COUNT(DISTINCT USERID)
cars 1
film 1
sports 2
关于mysql - 选择按两列分组的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15719210/