2012-10-29 154 views
2

我試圖根據IF條件更改where子句。查詢失敗,出於某種原因。我將不勝感激任何幫助。if-else在mysql中查詢where子句

謝謝!

 SELECT 
      c.id AS course, 
      cr.id AS criteriaid, 
      u.id AS userid, 
      ue.timestart AS otimestart, 
      (ue.timestart + cr.enrolperiod) AS ctimestart, 
      ue.timecreated AS otimeenrolled, 
      (ue.timecreated + cr.enrolperiod) AS ctimeenrolled 
     FROM 
      {user} u 
     INNER JOIN 
      {user_enrolments} ue 
     ON ue.userid = u.id 
     INNER JOIN 
      {enrol} e 
     ON e.id = ue.enrolid 
     INNER JOIN 
      {course} c 
     ON c.id = e.courseid 
     INNER JOIN 
      {course_completion_criteria} cr 
     ON c.id = cr.course 
     LEFT JOIN 
      {course_completion_crit_compl} cc 
     ON cc.criteriaid = cr.id 
     AND cc.userid = u.id 
     WHERE 
      cr.criteriatype = 5 
     AND c.enablecompletion = 1 
     AND cc.id IS NULL 
     AND    
     (
     IF (ue.timeextension IS NULL) 
       (ue.timestart > 0 AND ue.timestart + cr.enrolperiod < ? 
      OR ue.timecreated > 0 AND ue.timecreated + cr.enrolperiod < ?) 
     ELSE 
       (ue.timestart > 0 AND ue.timestart + ue.timextension < ? 
      OR ue.timecreated > 0 AND ue.timecreated + ue.timeextension < ?) 
     ) 
+0

「某些原因」幾乎總是不夠好;-)什麼是*精確*錯誤信息或問題? –

回答

0

根據您想要完成,正確的是什麼where子句可能是:

... 
where ... 
and (if(ue.timeextension IS NULL, 
     ue.timestart > 0 AND ue.timestart + cr.enrolperiod < ? 
      OR ue.timecreated > 0 AND ue.timecreated + cr.enrolperiod < ?, 
     ue.timestart > 0 AND ue.timestart + ue.timextension < ? 
      OR ue.timecreated > 0 AND ue.timecreated + ue.timeextension < ?); 
2

IF表達式的語法是:

IF(<cond-expr>, <then-expr>, <else-expr>) 

有一個在沒有ELSE關鍵字語法,你只需用逗號分隔兩個結果表達式。所以你表達的正確語法應該是:

AND IF(ue.timeextension IS NULL, 
     (ue.timestart > 0 AND ue.timestart + cr.enrolperiod < ?) 
     OR (ue.timecreated > 0 AND ue.timecreated + cr.enrolperiod < ?), 
     (ue.timestart > 0 AND ue.timestart + ue.timextension < ?) 
     OR (ue.timecreated > 0 AND ue.timecreated + ue.timeextension < ?)) 

你可以寫這另一種方法是:

AND ((ue.timestart > 0 AND ue.timestart + IFNULL(ue.timeextesion, cr.enrolperiod) < ?) 
    OR (ue.timecreated > 0 AND ue.timecreated + IFNULL(ue.timeextesion, cr.enrolperiod)) < ?) 
+0

第二個人工作..感謝很多! – user1783854

0

我想你可能會嘗試最後一節在這裏即

AND    
    (
    IF (ue.timeextension IS NULL) 
      (ue.timestart > 0 AND ue.timestart + cr.enrolperiod < ? 
     OR ue.timecreated > 0 AND ue.timecreated + cr.enrolperiod < ?) 
    ELSE 
      (ue.timestart > 0 AND ue.timestart + ue.timextension < ? 
     OR ue.timecreated > 0 AND ue.timecreated + ue.timeextension < ?) 
    ) 

as

AND    
    (
     (ue.timestart > 0 AND ue.timestart + 
      IFNULL(ue.timeextension , cr.enrolperiod) < ?) 
    OR (ue.timecreated > 0 AND ue.timecreated + 
      IFNULL (ue.timeextension, cr.enrolperiod) < ?) 
    )