开发者

Mysql - Select user only once when subscribed to multiple categories

Good day,

Currently I am working on a project, and I am kinda stuck. It is a relative simple t开发者_如何学Pythonable where this question is about (see this photo: http://cl.ly/5M0x ).

There is a user_id collumn and a categorie_id collumn, each representing an id from another table (users and categories). Now I am trying to get the number of users within each category which is simple and can be done like:

'SELECT COUNT(uc.user_id) as total FROM xs2media_users_categories as uc GROUP by uc.categorie_id'

However what I want is that when a user has been counted for a certain category it won't be counted for another categorie where it is subscribed to. So for example if user number four is subscribed to category 2, it will increment the count of that, but not for category 3 anymore, even though he could be subscribed to that category too.

Hope this makes sence.

Thanks.


The following query picks one category for each user, and then counts the nr of users per each category.

select categorie_id
      ,count(*)
  from (select user_id
              ,min(categorie_id) as categorie_id
          from xs2_media_users_categories
         group 
            by user_id
       ) u
  group
     by categorie_id;

Is this what you are looking for?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜