如何选择两列(外键)值并将其与主键匹配(它们具有相同的主键)MYSQL

5lwkijsr  于 2023-01-12  发布在  Mysql
关注(0)|答案(2)|浏览(151)

我有两张table,一个队和一场比赛。
团队:
| 识别号|团队名称|
| - ------|- ------|
| 1个|PSG|
| 第二章|操作手册|
ID是主键
匹配
| ID_团队_主页|ID_团队_离开|目标_球队_主场|球队客场进球|
| - ------|- ------|- ------|- ------|
| 1个|第二章|五个|四个|
| 第二章|1个|六个|1个|
ID_team_home和ID_team_away是外键,而我想要的结果是一个查询,它不创建表,而只是选择球队所有目标的总和
| 团队名称|团队_目标|
| - ------|- ------|
| PSG|六个|
| 操作手册|十个|
请帮帮忙
我试过很多解决方法,我用过求和,连接,case,if,子查询,但是没有效果,请帮助。大多数时候它只是把两行相加,然后给我一个完全不准确的答案。
选择www.example.com_name,SUM(matchs. goal_team_home)作为BPe,匹配时大小写。ID_team_home =球队. id然后SUM(matchs. goal_team_home)匹配时大小写。ID_team_away =装备. id然后SUM(matchs. goal_team_away)作为测试结束,球队在哪里匹配。ID_team_home =球队. id或匹配。ID_team_away =球队. id分组依据装备。装备team.team_name, SUM(matchs.goal_team_home) as BPe, CASE WHEN matchs.ID_team_home=team.id THEN SUM(matchs.goal_team_home) WHEN matchs.ID_team_away=equipe.id THEN SUM(matchs.goal_team_away) END as test from matchs,team WHERE matchs.ID_team_home=team.id or matchs.ID_team_away=team.id GROUP BY equipe.Equipes
排序依据测试

ocebsuys

ocebsuys1#

我们可以将并集方法与外部聚合结合使用:

SELECT t1.Team_name, SUM(t2.goal_team) AS Team_goals
FROM Team t1
INNER JOIN
(
    SELECT ID_team_home AS ID_team, goal_team_home AS goal_team FROM Matches
    UNION ALL
    SELECT ID_team_away, goal_team_away FROM Matches
) t2
    ON t2.ID_team = t1.ID
GROUP BY t1.Team_name
ORDER BY t1.Team_name;

该联合将所有团队/目标内联到两列中,然后按团队对中间结果进行聚合,以获得团队目标。

jvlzgdj9

jvlzgdj92#

使用LEFT连接将team连接到matchs(以防matchs中有一个团队没有任何行),并使用条件聚合:

SELECT t.Team_name,
       SUM(
         CASE t.ID 
           WHEN m.ID_team_home THEN m.goal_team_home 
           WHEN m.ID_team_away THEN m.goal_team_away
           ELSE 0 
         END
       ) Team_goals
FROM team t LEFT JOIN matchs m
ON t.ID IN (m.ID_team_home, m.ID_team_away)
GROUP BY t.ID
ORDER BY Team_goals;

请参见demo

相关问题