Question

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

Was it helpful?

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'

OTHER TIPS

You can use a variable, try This

set @a:='';

SELECT `student`.`id`, `student`.`firstname`, `student`.`lastname`,
IFNULL(@a:=`review`.`score`, @a:=0),
`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` = @a
WHERE `student`.`id` > '0'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top