mysql - MySql中子查询的问题

标签 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    |

最佳答案

为什么不重新设计您的数据库,就像您只有两张表一样,一张用于竞争对手,一张用于团队,如下所示:

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

关于mysql - MySql中子查询的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16996050/

相关文章:

mysql - 'having clause' : 中的未知列

mysql - 我可以在 Mysql 中计算两列之间的总和吗?

java - Android 以及如何处理用户数据库

php - InnoDB表锁定用于写入但允许读取

php - 格式化 MySQL 查询的结果,就好像它是从控制台运行的一样

php - 为什么对已经存在的标准函数使用自定义 sql 函数?

mysql - MongoDB存储以及MySQL XPath功能

java - 将Java连接到MySQL数据库

mysql - MySQL 过程中出现错误 1064

PHP - 格式化 HH :MM:SS to 12hr HH:MM:a string