MySql中子查询的问题

时间:2013-06-08 04:29:16

标签: mysql

我遇到了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    |

1 个答案:

答案 0 :(得分: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

查看我的fiddle demo