2017-01-14 58 views
-1

我有一個查詢,我想COUNT行。問題是,當我嘗試計算完全相同的查詢時,它正在打印9,但是當我運行查詢並打印行時,它只有5個(因爲它應該是)在連接表上做一個COUNT

以下是查詢的工作原理和顯示5行:

$results_quiz = $pdo->query("SELECT 
    sr.statistic_ref_id, 
    sr.quiz_id, 
    sr.user_id, 
    sr.total_time, 
    qm.name AS q_name, 
    qm.category_id, 
    qm.subcategory_id, 
    sc.sub_category_id, 
    sc.sub_category_name AS quiz_type, 
    pl.time, 
    pl.points, 
    COUNT(qs.correct_count) AS count_correct 
    FROM pro_quiz_statistic_ref AS sr 
    JOIN pro_quiz_master qm ON qm.id = sr.quiz_id 
    JOIN pro_quiz_subcategory sc ON sc.sub_category_id = qm.subcategory_id 
    JOIN user_points_log pl ON pl.quiz_id = sr.quiz_id AND pl.user_id = '$get_id' 
    JOIN pro_quiz_statistic qs ON qs.statistic_ref_id = sr.statistic_ref_id 
    WHERE 
    sr.user_id = '$get_id' AND 
    qs.correct_count = '1' 
    GROUP BY  
    sr.statistic_ref_id, 
    qs.correct_count 
    ORDER BY qm.name ASC"); 

上面的代碼工作像它應該,但是當我用這個:

$count_results_quiz = $pdo->query("SELECT COUNT(' 
    sr.statistic_ref_id, 
    sr.quiz_id, 
    sr.user_id, 
    sr.total_time, 
    qm.name AS q_name, 
    qm.category_id, 
    qm.subcategory_id, 
    sc.sub_category_id, 
    sc.sub_category_name AS quiz_type, 
    pl.time, 
    pl.points, 
    COUNT(qs.correct_count) AS count_correct') 
    FROM pro_quiz_statistic_ref AS sr 
    JOIN pro_quiz_master qm ON qm.id = sr.quiz_id 
    JOIN pro_quiz_subcategory sc ON sc.sub_category_id = qm.subcategory_id 
    JOIN user_points_log pl ON pl.quiz_id = sr.quiz_id AND pl.user_id = '$get_id' 
    JOIN pro_quiz_statistic qs ON qs.statistic_ref_id = sr.statistic_ref_id 
    WHERE 
    sr.user_id = '$get_id' AND 
    qs.correct_count = '1' 
    GROUP BY  
    sr.statistic_ref_id, 
    qs.correct_count 
    ORDER BY qm.name ASC")->fetchColumn(); 

它打印 「9」。有人知道爲什麼

+1

請參閱http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple- sql-query – Strawberry

+0

,因爲有9行'sr.user_id ='$ get_id'AND qs.correct_count ='1'' for them is true –

+0

但是,當我運行查詢時沒有顯示9行計數?當我刪除「AND qs.correct_count ='1'」時,它仍然在打印9,儘管表格中綁定了10行user_id – Kenneth

回答

0

我發現了另一個解決方案,將表分成兩個查詢/表。其中一個顯示超過0(至少1個)正確答案,另一個顯示0正確答案。這樣它也更符合我的需求。