Mysql 最受欢迎的客房

Mysql 最受欢迎的客房,mysql,Mysql,我在我的数据库中有这些数据,我希望得到用户最喜欢的空间 表名:favorit\u房间 id | userid | room_id| favorit 1 | 114 | 1 | 1 2 | 45 | 1 | 0 3 | 45 | 5 | 1 4 | 47 | 1 | 1 5 | 114

我在我的数据库中有这些数据,我希望得到用户最喜欢的空间

表名:
favorit\u房间

 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
我尝试按房间id和用户id分组,但没有成功。然后我想按最喜欢的顺序排列到最不喜欢的顺序。当然要注意最喜欢的顺序。它不是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和room_id是一起索引的,因此没有重复


我该如何实现这一点呢?谢谢。

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

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

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

SELECT room_id, count(userid) AS countusers 
FROM favorit_rooms 
WHERE favorit = 1
GROUP BY room_id
ORDER by countusers DESC LIMIT 5
应该是这个吗

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
应该是这个吗

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

这看起来很管用:),想试试另一个答案,看看区别吗?问题说明userid和room_id是索引在一起的,所以没有重复项。不需要如此不同。计数中的不同应该只用于计数不同的用户id,否则您将计数(例如用户id 45)五次,但应仅计数一次。这看起来很有效:),只想尝试另一个答案以查看差异问题说明用户id和房间id是索引在一起的,因此没有重复项。因此,distinct并不是真正需要的。distinct in count应该只用于count distinct userid,否则你会将例如userid 45计算五次,但应该只计算一次。如果没有distinct,你的工作也会更容易,正如你所说的索引。谢谢:)你的也很好用,而且没有你说的那样的清晰的索引。谢谢:)