MySQL IF什么都不返回

时间:2015-01-13 12:45:41

标签: mysql

我正在尝试做一些优化,目前发布mysql的工作是在结果上完成设置一个新的参数$class_subject ...所以我试着在mysql中计算得到这个......

SELECT
     class_grade.results                as results,
     subjects.subject                   as subject,
     subjects_pseudonyms.pseudonym      as pseudonym,
     IF( subjects_pseudonyms.pseudonym = null, subjects.subject, subjects_pseudonyms.pseudonym ) as class_subject
 FROM
     class_grade
 INNER JOIN class               ON class_grade.class_ID         = class.class_ID
 INNER JOIN subjects            ON class.subject_ID             = subjects.a_ID
 LEFT JOIN  subjects_pseudonyms ON class.subject_pseudonym_ID   = subjects_pseudonyms.a_ID
 WHERE
     class_grade.teacher_ID     = :teacher_id AND
     class_grade.class_ID       = :current_class_ID AND
     class_grade.report_set_ID  = :report_set_ID AND
     class_grade.student_ID     = :current_student_ID

在上面的查询中,pseudonym可能为空,如果是,我尝试将新变量class_subject设置为subjectpseudonym ... < / p>

查询运行正常,结果示例如下:

[results] => 71
[subject] => Law
[pseudonym] => 
[class_subject] => 

问题是,class_subject未填充..

我的IF()cond有问题吗?

谢谢, 约翰

1 个答案:

答案 0 :(得分:1)

您需要使用IS NULL代替= NULLISNULL() http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_isnull

  

可以使用ISNULL()代替=来测试值是否为NULL。   (使用=将值与NULL进行比较总是产生 false 。)