簡體   English   中英

SQL選擇查詢與計數

[英]Sql select query with count

我有一個fb_requests表。 在此處輸入圖片說明

我想基於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;

提前致謝。

您應該將HAVING sql語句與聚合函數一起使用
嘗試這個

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 
    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;

我認為是因為有聚合功能,請嘗試執行此操作。

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

請根據您的要求嘗試以下查詢

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;

請嘗試以下方法:

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;

讓我知道您是否不是從上述查詢中獲取的結果。

從fb_requests中選擇game_selected,其中user_id = 17 by game_selected按count(accept_status)<4分組;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM