我有很多关于我正在举办的比赛的数据,我希望以更好的格式呈现它。
有4张桌子;前两个是不言自明的,points
和extras
表基本上完全相同,它们只是存储在具有略微不同列名的不同表中。
users +----+---------------+------+ | id | name | team | +----+---------------+------+ | 1 | John Doe | 1 | | 2 | Jane Lane | 1 | | 3 | Jack Black | 4 | | 4 | Dan Bam | 3 | | 5 | Pam Jan | 2 | | 6 | Pop Tart | 2 | | 7 | John Q | 1 | | 8 | Hugo Strange | 3 | | 9 | Jimmy Neutron | 2 | +----+---------------+------+
teams +----+-----------------+ | id | name | +----+-----------------+ | 1 | Team Fun | | 2 | The Dream Team | | 3 | In It To Win It | | 4 | Buddies | +----+-----------------+
points +---------+--------+------------+ | user_id | points | event | +---------+--------+------------+ | 1 | 2 | Basketball | | 2 | 4 | Basketball | | 5 | 1 | Basketball | | 8 | 3 | Basketball | | 9 | 5 | Basketball | | 2 | 8 | Volleyball | | 5 | 5.5 | Volleyball | | 6 | 6.5 | Volleyball | | 7 | 2 | Volleyball | | 8 | 4 | Volleyball | | 9 | 9.5 | Volleyball | | 1 | 2.5 | Dodgeball | | 3 | 3 | Dodgeball | | 4 | 4 | Dodgeball | | 6 | 9 | Dodgeball | | 7 | 2.5 | Dodgeball | | 9 | 3 | Dodgeball | +---------+--------+------------+
extras +---------+--------+---------------------+ | user_id | points | description | +---------+--------+---------------------+ | 1 | 5 | Great Sportsmanship | | 3 | 10 | Team Player | | 8 | 5.5 | Most Improved | +---------+--------+---------------------+
我想写一个查询来返回特定团队参与的所有事件(和“额外”),团队所有成员的总分以及该事件中的参与成员。
下面的示例使用Team Fun(第1组):
+---------------------+--------+--------------------+------------+
| event | points | members | members_id |
+---------------------+--------+--------------------+------------+
| Basketball | 6 | John Doe,Jane Lane | 1,2 |
| Volleyball | 10 | Jane Lane,John Q | 2,7 |
| Dodgeball | 5 | John Doe,John Q | 1,7 |
| Great Sportsmanship | 5 | John Doe | 1 |
+---------------------+--------+--------------------+------------+
如果有人能帮我解决这个问题,我会很感激的!
这是一个带有上述数据模式的SQLFiddle - http://sqlfiddle.com/#!2/e8f97a
答案 0 :(得分:1)
您可以使用UNION
获取额外内容和积分:
SELECT user_id, points, event
FROM points
UNION ALL
SELECT user_id, points, description AS event
FROM extras
然后使用此功能,您可以使用SUM
和几个GROUP_CONCAT
来编译您的信息:
SELECT P.event, SUM(P.points) AS points,
GROUP_CONCAT(U.name) AS members, GROUP_CONCAT(U.id) AS members_id
FROM teams T
INNER JOIN users U ON T.id = U.team
INNER JOIN
(
SELECT user_id, points, event
FROM points
UNION ALL
SELECT user_id, points, description AS event
FROM extras
) P ON U.id = P.user_id
WHERE T.id = @teamId
GROUP BY P.event