Search code examples
mysqlleft-joinaliasmysql-error-1054ifnull

MySQL IFNULL, Alias and LEFT JOIN result an Unknown column error


This is my simplified query:

SELECT `student`.`id`, `student`.`firstname`, `student`.`lastname`,
IFNULL(`review`.`score`, '0') AS `adminreview_score`,
`reviewcolor`.`color` AS adminreview_color FROM (`student`)
LEFT JOIN `review` ON `review`.`student_id` = `student`.`id` AND
review.reviewtype_id = 13
LEFT JOIN `reviewcolor` ON `reviewcolor`.`score` = `adminreview_score`
WHERE `student`.`id` > '0'

And this is the error I get:

Error Number: 1054

Unknown column 'adminreview_score' in 'on clause'

Note that there may be no row in review table with the situation:

`review`.`student_id` = `student`.`id` AND review.reviewtype_id = 13

In this situation, I want adminreview_score to be set as 0, and I hope reviewcolor.color be NULL or empry ()

Thank you


Solution

  • Try this: (I replaced the alias with the actual expression. Note that aliases from the SELECT clause can't be used in the rest of the SQL expression.)

    SELECT `student`.`id`, `student`.`firstname`, `student`.`lastname`,
    IFNULL(`review`.`score`, '0') AS `adminreview_score`,
    `reviewcolor`.`color` AS adminreview_color 
    FROM (`student`)
        LEFT JOIN `review` ON `review`.`student_id` = `student`.`id` AND review.reviewtype_id = 13
        LEFT JOIN `reviewcolor` ON `reviewcolor`.`score` = IFNULL(`review`.`score`, '0')
    WHERE `student`.`id` > '0'