在mysql中使用左连接表的条件

时间:2016-05-02 09:15:35

标签: php mysql codeigniter-2

我有测验表,显示在图像中。quiz table

和测验结果历史记录表,如user_quiz_results table

我在这两个表之间写了左连接查询。 我的查询如下:

  select q.*
       , c.name as catname 
       , qrh.q_complete
       , q s.test_type
       , qs.questionid
       , sum(qrh.score) as score1
       , sum(qrh.total_questions) as tot_que 
    from categories c
       , quiz q 
    left 
    join user_quiz_results_history qrh 
      on qrh.quiz_id = q.quizid 
    left 
    join quizquestions qq 
      on qq.quizid = q.quizid 
    left
    join questions qs 
      on qs.subcatid = qq.subjectid 
   where c.catid = q.catid 
     AND q.catid = 1
     AND q.status = 'Active' 
     AND q.enddate >= '2016-05-02' 
   group 
        by q.quizid

此查询为结果提供所有测验表数据和相关的user_quiz_results表。

如果我使用条件为左连接表编写查询,如userid = 90,我不会得到任何数据。

我想要测验的所有数据,如果表格中有userid = 90的结果,请从表user_quiz_history.avg(得分)中获取数据。

1 个答案:

答案 0 :(得分:0)

在左连接子句上写条件。

select q.* , qrh.q_complete , sum(qrh.score) as score1 , sum(qrh.total_questions) as tot_que from categories c , quiz q left join user_quiz_results_history qrh on qrh.quiz_id = q.quizid AND qrh.userid=84 where  q.catid = 1 AND q.status = 'Active' AND q.enddate >= '2016-05-02' group by q.quizid