前几天我刚开始学习SQL,遇到了绊脚石。我有一些看起来像这样的代码:
SELECT player, SUM(wins) from (
SELECT win_counts.player, win_counts.wins
from win_counts
UNION
SELECT lose_counts.player, lose_counts.loses
from lose_counts
group by win_counts.player
) as temp_alias
这是我得到的错误:
错误:缺少FROM-clause条目表" win_counts" 第7行:按win_counts.player分组
此win_counts表包含玩家ID列表以及他们拥有的匹配数。 lose_counts表包含玩家ID列表以及丢失的匹配数。最终我需要一个玩家ID表和每个玩家所玩的匹配总数。
感谢您的帮助。对不起,我没有更多的信息......我对sql的理解非常简陋。
答案 0 :(得分:5)
分组似乎位于错误的位置。
SELECT player, SUM(wins) as SumWinsLoses
FROM(
SELECT win_counts.player, win_counts.wins
FROM win_counts
UNION ALL -- as Gordon points out 'ALL' is likely needed, otherwise your sum will be
-- off as the UNION alone will distinct the values before the sum
-- and if you have a player with the same wins and losses (2),
-- the sum will return only 2 instead of (4).
SELECT lose_counts.player, lose_counts.loses
FROM lose_counts) as temp_alias
GROUP BY player
我们很清楚,虽然SUm(Wins)将总和输赢,因为“胜利”字段联盟中的第一个名称是使用的名称。因此,球员的胜负将被汇总。
这是一个有效的SQL FIddle通知,没有联合所有......玩家#2的计数不正确。
答案 1 :(得分:1)
你已经有了一个很好的答案和其他人的评论。为了您的启发:
在某些情况下,在联合之前聚合可能更有效。
select player, sum(wins) from (
select player, count(*) as wins
from win_counts
group by player
UNION ALL /* without ALL you'll eliminate duplicate rows */
select player, count(*) as losses
from lose_counts
group by player
) as t
group by player
如果每位球员都有胜负,这也应该给出相同的结果:
select wins.player, wins + losses as total_matches
from
(
select player, count(*) as wins
from win_counts
group by player
) as wins
inner join
(
select player, count(*) as losses
from lose_counts
group by player
) as losses
on losses.player = wins.player
缺少赢/输的修复是一个完整的外部联接:
select
coalesce(wins.player, losses.player) as player,
coalesce(wins. 0) + coalesce(losses, 0) as total_matches
from
(
select player, count(*) as wins
from win_counts
group by player
) as wins
full outer join
(
select player, count(*) as losses
from lose_counts
group by player
) as losses
on losses.player = wins.player
这些复杂的查询应该让您了解为什么对于属于一起的数据使用单独的表是个坏主意。在这种情况下,您可能更喜欢将所有匹配记录为胜利,损失(或关系)的单个表。