除以零以进行分类处理

时间:2013-09-23 15:37:37

标签: mysql sql null zero

您好我的数据库中有两个表:用户和评级。我需要按评级对它们进行排序:

SELECT * 
FROM users
LEFT JOIN ratings ON users.id = ratings.id
ORDER BY ratings.total_value / ratings.total_votes DESC 
LIMIT 0 , 30

有时total_value值为null,我应该添加其他条件来检查这些值是否为空?

3 个答案:

答案 0 :(得分:0)

我认为COALESCE()可以在这里工作:

ORDER BY COALESCE(ratings.total_value, 0) / ratings.total_votes DESC 

答案 1 :(得分:0)

您可以使用COALESCE(ratings.total_value, 0)返回第一个非空值。如果ratings.total_valueNULL,那么您将获得0

http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce

答案 2 :(得分:0)

我对select 1 / 0的简单测试给出了一个空值,所以我甚至不知道你是否需要关心