如何使用2列COUNTS等于INNER JOIN

时间:2016-01-12 03:31:02

标签: mysql sql inner-join

我正在尝试执行以下查询:

SELECT wwpqsr.statistic_ref_id, 
       wwpqsr.create_time, 
       wwpqm.name
  FROM wp_wp_pro_quiz_statistic_ref AS wwpqsr
         INNER JOIN wp_wp_pro_quiz_statistic AS wwpqs 
           ON (  wwpqs.statistic_ref_id = wwpqsr.statistic_ref_id 
               AND COUNT(wwpqs.correct_count) AS correct = 
                   COUNT(wwpqs.incorrect_count) AS incorrect)
         INNER JOIN wp_wp_pro_quiz_master AS wwpqm 
           ON (wwpqm.id = wwpqsr.quiz_id)
    WHERE wwpqsr.user_id = 1;

我需要在最后对结果进行限制,但由于功能目的尚未显示,因为我只需要从p_wp_pro_quiz_statistic表中获取结果,其中correct_count表的计数为{{ 1}}等于incorrect_count列中的行数。我怎么能在INNER JOIN中这样做?所有1个查询?可能?上面的代码返回空结果,它不应该是空结果。应该怎样做这样的事情?

1 个答案:

答案 0 :(得分:2)

正如我在评论中所说,除非是子查询中的字段,否则不能将聚合函数用作where子句。对于您的情况,我认为您正在寻找:

SELECT wwpqsr.statistic_ref_id, 
       wwpqsr.create_time, 
       wwpqm.name
  FROM wp_wp_pro_quiz_statistic_ref AS wwpqsr
         INNER JOIN wp_wp_pro_quiz_statistic AS wwpqs 
           ON (  wwpqs.statistic_ref_id = wwpqsr.statistic_ref_id )
         INNER JOIN wp_wp_pro_quiz_master AS wwpqm 
           ON (wwpqm.id = wwpqsr.quiz_id)
    WHERE wwpqsr.user_id = 1
    GROUP 
       BY wwpqsr.statistic_ref_id, 
          wwpqsr.create_time, 
          wwpqm.name
    HAVING COUNT(wwpqs.correct_count) = COUNT(wwpqs.incorrect_count);