1

当我加入一个空表并将其添加到kills_total字段时, kills_total 值显示NULL

SELECT 
       alias.name alias, team.name team, sid.steam_id steam_id,
       (SUM(ws1.kills) + SUM(ws2.kills) + SUM(spnr.kills)) kills_total
FROM pickup
            JOIN player ON player.pickup_id = pickup.id
            JOIN team ON player.team_id = team.id
            JOIN sid ON player.sid_id = sid.id
            JOIN alias ON player.alias_id = alias.id
            LEFT JOIN weapon_stats_1 ws1 ON ws1.pickup_id = pickup.id AND ws1.player_id = player.id
            LEFT JOIN weapon_stats_2 ws2 ON ws2.pickup_id = pickup.id AND ws2.player_id = player.id
            LEFT JOIN spanner_stats spnr ON spnr.pickup_id = pickup.id AND spnr.player_id = player.id
WHERE pickup.logfile_name = 'srv-20130725-2151-log' GROUP BY player.id ORDER BY kills_total DESC

这是结果:

失败

SELECT 
       alias.name alias, team.name team, sid.steam_id steam_id,
       (SUM(ws1.kills) + SUM(ws2.kills)) kills_total
FROM pickup
            JOIN player ON player.pickup_id = pickup.id
            JOIN team ON player.team_id = team.id
            JOIN sid ON player.sid_id = sid.id
            JOIN alias ON player.alias_id = alias.id
            LEFT JOIN weapon_stats_1 ws1 ON ws1.pickup_id = pickup.id AND ws1.player_id = player.id
            LEFT JOIN weapon_stats_2 ws2 ON ws2.pickup_id = pickup.id AND ws2.player_id = player.id
WHERE pickup.logfile_name = 'srv-20130725-2151-log' GROUP BY player.id ORDER BY kills_total DESC

这是我从查询中删除空表时的结果:

在此处输入图像描述

如何加入spanner_stats表,如果它为空,则什么都不做(即 SUM(0)),因此ws1ws2值被 SUM()med up 并显示在kills_total中,即使正在加入的第三个表没有单个匹配“thirdTable.pickup_id =pick.id AND thirdTable.player_id = player.id”的行?

4

2 回答 2

3

尝试这个:

SELECT 
       alias.name alias, team.name team, sid.steam_id steam_id,
       (SUM(IFNULL(ws1.kills,0)) + SUM(IFNULL(ws2.kills,0)) + SUM(IFNULL(spnr.kills,0))) kills_total
FROM pickup
            JOIN player ON player.pickup_id = pickup.id
            JOIN team ON player.team_id = team.id
            JOIN sid ON player.sid_id = sid.id
            JOIN alias ON player.alias_id = alias.id
            LEFT JOIN weapon_stats_1 ws1 ON ws1.pickup_id = pickup.id AND ws1.player_id = player.id
            LEFT JOIN weapon_stats_2 ws2 ON ws2.pickup_id = pickup.id AND ws2.player_id = player.id
            LEFT JOIN spanner_stats spnr ON spnr.pickup_id = pickup.id AND spnr.player_id = player.id
WHERE pickup.logfile_name = 'srv-20130725-2151-log' GROUP BY player.id ORDER BY kills_total DESC

本质上,您是在告诉 MySql 使用 0 而不是NULL 左连接没有记录。看看 IFNULL() http://www.w3schools.com/sql/sql_isnull.asp

如果我相信任何组件为 NULL,则 SQL SUM() 函数将返回 NULL。

于 2013-07-26T04:13:12.023 回答
1

也许您可以尝试使用IFNULL()

IFNULL(expr1,expr2)

如果 expr1 不为 NULL,则 IFNULL() 返回 expr1;否则返回 expr2。IFNULL() 返回一个数字或字符串值,具体取决于使用它的上下文。

看看下面的例子来展示差异。

SQL 小提琴演示

于 2013-07-26T04:12:46.473 回答