Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

mysql - Make a COUNT on JOIN tables

I have a query which I want to COUNT the rows. The problem is when I try to count the exact same query it's printing 9 but when I run the query and print the rows it's only 5 (as it should be)

Here is the query that works and show the 5 rows:

$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"); 

The above code works like it should but when I use this:

$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(); 

it's printing "9". Anyone knows why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found another solution by splitting the tables into two queries/tables. One of them showing more than 0 (at least 1) correct answer and the other one showing 0 correct answers. This way it also fits better to my needs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...