您的 SQL 语法有误...在 'float) / CAST(rating_count AS float)) as average_rating from document' 附近

You have an error in your SQL syntax...near 'float) / CAST(rating_count AS float)) as average_rating from document'

查询内容如下

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

我不明白为什么会出现语法错误。

这样试试:

select id, IF(rating_count = 0, null, 
CAST(rating_sum AS DECIMAL(10,6)) / CAST(rating_count AS DECIMAL(10,6))) as average_rating 
from document d left join document_aggregate_rating 
using (id) where id in (123);

MySQL documentation 说:

The type for the result can be one of the following values:

  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

您实际上不必执行演员表。即使两个参数都是整数,除法也会产生小数。此外,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);

聚合保证返回一行,即使没有匹配项。