0

我在这里有这个计算/查询:

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 我不认为?

4

1 回答 1

4

我认为这是一个空问题(使用您的 LEFT JOIN,这可能很容易发生)。

NULL + 1 + 2 = NULL

所以使用COALESCE(if null then...) 运算符

所以

SELECT  u.username,
        (COALESCE(a.totalCount, 0) * 7) +
        (COALESCE(b.totalCount, 0) * 3) +
        (COALESCE(c.totalCount, 0) * 1) AS totalScore

和一点SqlFiddle

于 2013-01-28T17:32:20.853 回答