以下是查询
select id, IF(rating_count = 0, null, CAST(rating_sum AS float) / CAST(rating_count AS float)) as average_rating
from document d left join document_aggregate_rating using (id) where id in (123);
我得到的错误
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'float) / CAST(rating_count AS float)) as average_rating from document' at line 1
我不知道为什么会出现语法错误.
解决方法:
您实际上不必进行演员表转换.即使两个参数都是整数,该除法也会产生一个十进制数.而且,nullif()比if()更短(也更标准):
select id, rating_sum / nullif(rating_count, 0) as average_rating
from document d left join
document_aggregate_rating dar
using (id)
where id = 123;
最后,不清楚这些列来自何处.但是,如果两者都来自document_aggregate_rating,则可以在不使用联接的情况下用词组查询:
select 123 as id, max(rating_sum) / nullif(max(rating_count), 0) as average_rating
from document_aggregate_rating dar
where id in (123);
聚合保证即使没有匹配项,也返回一行.
标签:mysql-error-1064,sql,mysql
来源: https://codeday.me/bug/20191027/1943944.html