[英]How to write a SQL query for this logic (has_many, belongs_to association)?
The goal of this SQL query is to return the user with the most fight wins AND a count of the wins. 该SQL查询的目标是使用户获得最多的获胜次数和获胜次数。
I have two tables: users and fights. 我有两个表:用户和打架。
User has many fights Fight belongs to user 用户有很多战斗战斗属于用户
Fight has the following columns of concern: 格斗涉及以下几列:
As you can see, a user can be a challenger or a challengee, but not both. 如您所见,用户可以是挑战者,也可以是挑战者,但不能同时是两者。
How would I write the SQL for this? 我将如何为此编写SQL?
What about this? 那这个呢?
SELECT a.fighter, COUNT(*) AS wins
FROM (SELECT challenger_id AS fighter
FROM fights
WHERE challenger_won = TRUE
UNION ALL
SELECT challengee_id AS fighter
FROM fights
WHERE challenger_won = FALSE
) AS a
GROUP BY a.fighter;
If challenger_won
is NULL, both queries in the UNION will ignore the row, as required. 如果
challenger_won
为NULL,则UNION中的两个查询将根据需要忽略该行。
If you don't like UNION ALL, you can use, instead: 如果您不喜欢UNION ALL,可以使用:
SELECT a.fighter, SUM(a.wins) AS wins
FROM (SELECT challenger_id AS fighter, 'R' AS role, COUNT(*) AS wins
FROM fights
WHERE challenger_won = TRUE
GROUP BY fighter, role
UNION
SELECT challengee_id AS fighter, 'E' AS role, COUNT(*) AS wins
FROM fights
WHERE challenger_won = FALSE
GROUP BY fighter, role
) AS a
GROUP BY a.fighter;
The first part of the UNION generates rows with 'R' as role (for 'challengeR won') and the fighter ID and a count of the fights won. UNION的第一部分生成以“ R”为角色的行(对于“ challengeR won”),以及战斗机ID和获胜次数。 The second part generates rows with 'E' as role (for 'challengeE won') and the fighter ID and a count of the fights won.
第二部分生成以“ E”为角色的行(用于“ challengeE won”),战斗机ID和获胜次数。 The role is necessary in case some fighter won 3 fights as challenger and 3 fights as challengee;
如果某些战斗机以挑战者身份赢得3场战斗并以挑战者身份赢得3场战斗,则该角色是必要的; without the role, the two entries with the same fighter and count would be collapsed into one.
如果没有角色,则具有相同战斗机和人数的两个条目将合为一体。 You then sum the wins for each fighter in each role.
然后,您可以总结每个角色中每个战士的胜利。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.