MySQL查询 - 跨多个表的多个和,需要忽略空值

时间:2018-05-01 06:15:36

标签: mysql sql

我正在尝试从5个不同的表格中执行下面的竖起大拇指减去竖起大拇指,然后将所有这些值合并在一起,如果所有' commthumbs'返回一行,但是如果一个或多个' commthumbs'没有行然后它返回一个空值。我尝试使用下面第一个LEFT JOIN中所示的IFNULL作为例子。我也尝试过ISNULL和COALESCE代替IFNULL,但似乎仍无法让它发挥作用。关于我做错了什么的建议?

load

1 个答案:

答案 0 :(得分:0)

试试这个

  SELECT 
        user.userID, user.username,
        SUM(IFNULL(a.commthumbs,0)+IFNULL(b.commthumbs,0)+IFNULL(c.commthumbs,0)+IFNULL(d.commthumbs,0)) AS 'commthumbs', 
        IFNULL(e.fixthumbs,0) AS 'fixthumbs'
    FROM
        user

    LEFT JOIN (
        SELECT 
        userID, SUM(IFNULL(gameCommThUp,0)-IFNULL(gameCommThDown,0)) AS 'commthumbs'
        FROM
        gamecomm
        GROUP BY userID) a ON a.userID = user.userID

    LEFT JOIN (
        SELECT 
        userID, SUM(IFNULL(fixCommThUp,0)-IFNULL(fixCommThDown,0)) AS 'commthumbs'
        FROM 
        fixcomm
        GROUP BY userID) b ON b.userID = user.userID

    LEFT JOIN (
        SELECT 
        userID, SUM(IFNULL(replyCommThUp,0)-IFNULL(replyCommThDown,0)) AS 'commthumbs'
        FROM gamereply
        GROUP BY userID) c ON c.userID = user.userID

    LEFT JOIN (
        SELECT userID, SUM(IFNULL(fixReplyThUp,0)-IFNULL(fixReplyThDown,0)) AS 'commthumbs'
        FROM fixreply
        GROUP BY userID) d ON d.userID = user.userID

    LEFT JOIN (
        SELECT 
        userID, SUM(IFNULL(fixThUp,0)-IFNULL(fixThDown,0)) AS 'fixthumbs'
        FROM 
        fix
        GROUP BY userID) e ON e.userID = user.userID

    WHERE user.userID = 2;