我在这里有这个计算/查询:
SELECT u.username,
(a.totalCount * 7) +
(b.totalCount * 3) +
(c.totalCount * 1) AS totalScore
FROM users u
LEFT JOIN
(
SELECT user_id, COUNT(user_id) totalCount
FROM items
GROUP BY user_id
) a ON a.user_id= u.user_id
LEFT JOIN
(
SELECT user_id, COUNT(user_id) totalCount
FROM comments
GROUP BY user_id
) b ON b.user_id= u.user_id
LEFT JOIN
(
SELECT user_id, COUNT(user_id) totalCount
FROM ratings
GROUP BY user_id
) c ON c.user_id = u.user_id
ORDER BY totalScore DESC LIMIT 10;
问题是,如果a,b或c返回0,则整个totalScore
为0.我无法弄清楚发生了什么?我没有将最终的结果乘以0,我不认为?
答案 0 :(得分:4)
我认为这是一个空问题(使用LEFT JOIN,这可能很容易发生)。
NULL + 1 + 2 = NULL
所以使用COALESCE
(如果为null然后...)运算符
所以
SELECT u.username,
(COALESCE(a.totalCount, 0) * 7) +
(COALESCE(b.totalCount, 0) * 3) +
(COALESCE(c.totalCount, 0) * 1) AS totalScore
和一点SqlFiddle