多次并集和联接操作后的求和列

bqjvbblv  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(293)

我期待着总和的一列球员属于某个特定的球队的基础上。我有一张球员桌和一张团队桌。目前,我没有任何问题,只是由于某种原因,它不会对我的查询的最后一部分求和。下面是我的代码示例:

Select SUM(points)
from (select points
from player
Join team on player.full_name=team.player1
Where team.team_id = 8
and week =9
UNION
Select points
FROM player 
JOIN team on player.full_name=team.player2 
Where team.team_id = 8
and week =9
UNION
Select points
FROM player 
JOIN team on player.full_name=team.player3
Where team.team_id = 8
and week =9
UNION
Select points
FROM player 
JOIN team on player.full_name=team.player4
Where team.team_id = 8
and week =9

任何关于为什么会发生这种情况或更好的潜在方式来完成这将不胜感激!

u3r8eeie

u3r8eeie1#

您的查询似乎不完整,必须使用 UNION ALL 为了得到完整的总数(f)2或更多的球员有相同的分数 UNION DISTINCT 将消除这些行):

SELECT
    SUM( points )
FROM (
    SELECT
        points
    FROM player
    JOIN team ON player.full_name = team.player1
    WHERE team.team_id = 8
    AND week = 9
    UNION ALL
    SELECT
        points
    FROM player
    JOIN team ON player.full_name = team.player2
    WHERE team.team_id = 8
    AND week = 9
    UNION ALL
    SELECT
        points
    FROM player
    JOIN team ON player.full_name = team.player3
    WHERE team.team_id = 8
    AND week = 9
    UNION ALL
    SELECT
        points
    FROM player
    JOIN team ON player.full_name = team.player4
    WHERE team.team_id = 8
) d

但我相信你的团队表格需要修改以获得更好的效率
请注意,使用 UNION = UNION DISTINCT i、 e.如果省略,则假定为“不同”。
这可能更有效:

SELECT
    SUM( player.points )
FROM player
WHERE player.full_name IN (
    SELECT distinct
        case when cj.n = 1 then team.player1
             when cj.n = 2 then team.player2
             when cj.n = 3 then team.player3
             when cj.n = 4 then team.player4
        end
    FROM team
    cross join (
       select 1 as n union all
       select 2 as n union all
       select 3 as n union all
       select 4 as n
       ) cj
    WHERE team.team_id = 8
    )
AND player.week = 9    ;

相关问题