当我加入一个空的表并将其添加到 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)),所以 ws1 和 ws2 值为SUM()med up并显示在 kills_total 中,即使正在连接的第三个表没有单行匹配“thirdTable.pickup_id = pickup.id AND thirdTable.player_id = player .ID“
答案 0 :(得分: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。我相信。
答案 1 :(得分:1)
也许您可以尝试使用IFNULL()
<强> IFNULL(表达式1,表达式2)强>
如果expr1不为NULL,则IFNULL()返回expr1;否则它会返回 表达式2。 IFNULL()返回一个数字或字符串值,具体取决于 使用它的上下文。
看一下下面的例子来说明差异。