MySQL IFNULL,Alias和LEFT JOIN导致一个Unknown列错误

时间:2012-07-02 19:45:20

标签: mysql left-join alias mysql-error-1054 ifnull

这是我的简化查询:

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'

这是我得到的错误:

Error Number: 1054

Unknown column 'adminreview_score' in 'on clause'

请注意,review表中可能没有符合以下情况的行:

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

在这种情况下,我希望将adminreview_score设置为0,我希望reviewcolor.colorNULL或empry(

谢谢

2 个答案:

答案 0 :(得分:1)

试试这个:(我用实际表达式替换别名。请注意,SELECT子句中的别名不能用于SQL表达式的其余部分。)

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'

答案 1 :(得分:1)

您可以使用变量,试试这个

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'