得到最喜欢的房间mysql

时间:2016-08-12 15:25:59

标签: mysql

我在我的数据库中有这些数据,我想让大多数room_id得到用户的青睐。

表名:favorit_rooms

 id    |   userid   |  room_id|   favorit

  1    |  114       | 1       |    1
  2    |  45        | 1       |    0
  3    |  45        | 5       |    1
  4    |  47        | 1       |    1
  5    |  114       | 3       |    1
  6    |  120       | 1       |    1
  7    |  114       | 2       |    1
  8    |  45        | 2       |    1
  9    |  45        | 3       |    1
 10    |  45        | 12      |    1
 11    |  131       | 1       |    0

我尝试按room_id和userid分组,但没有工作。然后我想通过最喜欢的顺序来订购它们。当然要注意那个青睐不是0。

 SELECT id,room_id,count(userid) as countusers FROM favorit_rooms 
 GROUP BY room_id,favorit  
 ORDER by room_id,favorit desc LIMIT 5

我希望的结果是:

       room_id    countusers 

        1          3        
        2          2        
        3          2        
        5          1        
        12         1        

userid AND room_id是索引在一起所以没有dublicates。

我如何实现这一点。

2 个答案:

答案 0 :(得分:1)

看起来您只需要稍微更改分组并添加where子句。这应该做你想要的:

SELECT room_id, count(userid) AS countusers 
FROM favorit_rooms 
WHERE favorit = 1
GROUP BY room_id
ORDER by countusers DESC LIMIT 5

答案 1 :(得分:1)

应该是这个

SELECT  room_id, count(distinct userid) as countusers 
FROM favorit_rooms 
WHERE favorit = 1
GROUP BY room_id,favorit  
ORDER by count(distinct userid) desc LIMIT 5