带有count的sql select查询

时间:2014-01-21 09:18:36

标签: mysql sql select count

我有一个fb_requests表。 enter image description here

我想基于accept_status选择game_selected列,如果accept_status count< 4,我想选择那些行。努力让它运作起来,请帮我解决这个问题。

这是我的创建表代码

CREATE TABLE `fb_requests` (                                              
               `id` int(60) NOT NULL AUTO_INCREMENT,                                   
               `user_id` int(60) DEFAULT NULL,                                         
               `fb_user_id` varchar(255) DEFAULT NULL,                                 
               `request_id` varchar(255) DEFAULT NULL,                                 
               `game_selected` int(60) DEFAULT NULL,                                   
               `accept_status` int(60) DEFAULT NULL COMMENT '0 = pending 1 = accept',  
               `created_date` datetime DEFAULT NULL,                                   
               `modified_date` datetime DEFAULT NULL,                                  
               PRIMARY KEY (`id`)                                                      
             ) ENGINE=MyISAM AUTO_INCREMENT=190 DEFAULT CHARSET=latin1    

试过这段代码。我知道它在语法上不正确但是尝试过。

Select 
    game_selected 
from 
    fb_requests
where 
    user_id = 17 
    && 
    (
        count(accept_status =1) < 4
    ) 
group by 
    game_selected;

提前致谢。

6 个答案:

答案 0 :(得分:1)

你应该使用带有聚合函数的HAVING sql语句
试试这个

Select game_selected from fb_requests
where user_id=17 
group by game_selected
having count(accept_status)<4;

答案 1 :(得分:1)

试试这个

    Select game_selected from fb_requests
    where user_id=17 
    group by game_selected
    having count(accept_status)<4;

<强>更新

    Select game_selected from fb_requests
    where user_id=17 and accept_status=1
    group by game_selected
    having count(accept_status)<4;

答案 2 :(得分:1)

我认为这是因为聚合函数,试试这个。

Select game_selected 
from fb_requests
where user_id=17
group by game_selected
HAVING COUNT(accept_status) < 4;

答案 3 :(得分:1)

请根据您的要求尝试以下查询

Select game_selected,count(accept_status) as as_cnt
    from 
        fb_requests
    where 
        user_id = 17 
    group by 
        game_selected
 having as_cnt < 4;

  

仅查询标记为“1”的accept_status

    Select 
        game_selected,sum(accept_status) as as_cnt
    from 
        fb_requests
   where 
            user_id = 17 
        group by 
            game_selected
     having as_cnt < 4;

答案 4 :(得分:1)

尝试以下:

Select fbr1.game_selected,fbr1.* from fb_requests fbr1 JOIN 
(select id,accept_status from fb_requests where accept_status =1 limit 4) fbr2
 ON fbr1.id=fbr2.id where fbr1.user_id = 17;

如果您没有查找从上述查询中获取的结果,请告诉我。

答案 5 :(得分:0)

从fb_requests中选择game_selected,其中user_id = 17 group by game_selected has count(accept_status)&lt; 4;