0

我在 MySql 中遇到问题,请帮助我。

在这个例子中,我有两张表,一张是一组竞争对手的结果,另一张是定义哪三个竞争对手组成一个团队。实际上,我还有许多其他表,但它们并不是真正需要描述这个问题。

Table with results for each competitor
| competitor_id | result1 | result2 | result3 | result4 |
|       1       |    1    |    1    |    1    |     1   |
|       2       |    1    |    2    |    2    |     1   |
|       3       |    2    |    3    |    2    |     1   |
|       4       |    1    |    5    |    3    |     2   |
|       5       |    4    |    3    |    2    |     3   |
|       6       |    3    |    2    |    1    |     2   |
|       7       |    2    |    1    |    4    |     2   |
|       8       |    2    |    1    |    2    |     1   |
|       9       |    1    |    2    |    3    |     2   |

Table showing teams
| team_id | competitor1 | competitor3 | competitor3 |
|    1    |      1      |       3     |       4     |
|    2    |      2      |       8     |       9     |
|    3    |      7      |       6     |       5     |

我现在想创建一个查询,为我提供每个团队的总和。我需要一个查询(可能带有子查询),因为我需要对总结果进行排序。

换句话说,我需要一个结果集给我 team.id 按每个团队的总结果排序的 desc。

任何人?

编辑:这是显示所需结果的更新

首先,让我们总结每个竞争对手的结果:

Competitor 1: 1+1+1+1=4
Competitor 2: 1+2+2+1=6
Competitor 3: 2+3+2+1=8
Competitor 4: 1+5+3+2=11
Competitor 5: 4+3+2+3=12
Competitor 6: 3+2+1+2=8
Competitor 7: 2+1+4+2=9
Competitor 8: 2+1+2+1=6
Competitor 9: 1+2+3+2=8

然后让我们看一下团队​​表。

Team 1 consists of competitors 1, 3 and 4.  
Team 2 consists of competitors 2, 8 and 9.  
Team 3 consists of competitors 7, 6 and 5.  

Total sum of team with id = 1 is 4+8+11=23  
Total sum of team with id = 2 is 6+6+8=20  
Total sum of team with id = 3 is 9+8+12=29  

鉴于所有这些,我希望我的结果集是

| id | team_sum |
| 3  |    29    |
| 1  |    23    |
| 2  |    20    |
4

1 回答 1

1

为什么不重新设计您的数据库,就像您只有两张表一样,一张competitors和一张team

Competitors Table:
`competitor_id`, `team_id`, `result1`, `result2`, `result3`, `result4`

Team Table:
`team_id`, `team_name`

您的查询将非常简单,例如:

SELECT A.team_id, B.team_name, SUM(result1+result2+result3+result4) as TotalResult
FROM competitors A
INNER JOIN team B
ON A.team_id=B.team_id
GROUP BY A.team_id, B.team_name

看我的小提琴演示

于 2013-06-08T05:46:41.073 回答