2016-08-12 72 views
0

我在我的数据库中有这个数据,我想得到大多数room_id得到了用户的青睐。获取最优惠的房间mysql

表名: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和用户ID,但没有工作tryed到组。然后我想以最低的价格订购它们。当然,请注意那个偏好不是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   

用户名和ROOM_ID是指数一起,所以没有dublicates。

我该如何做到这一点,谢谢。

回答

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 
+0

你也没有明显的正是你说其索引的工作更容易。谢谢:) –

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 
+0

这看起来工作:),想尝试其他答案只看到差异 –

+0

这个问题指出,_userid和room_id是索引在一起,所以没有duplicateates._如此明显不是真的需要。 – jpw

+0

计数中的唯一数值应该仅用于计数唯一的用户ID,否则您计数例如用户45五次而只应计为一次。 – scaisEdge