我有一个mysql表,其中包含团队比赛的数据。
目的:
计算其他SquadID
与Team
共享相同的SquadID=21
值的次数
// Selections table
+--------+---------+------+
| GameID | SquadID | Team |
+--------+---------+------+
| 1 | 5 | A |
| 1 | 7 | B |
| 1 | 11 | A |
| 1 | 21 | A |
| 2 | 5 | A |
| 2 | 7 | B |
| 2 | 11 | A |
| 2 | 21 | A |
| 3 | 5 | A |
| 3 | 7 | B |
| 3 | 11 | A |
| 3 | 21 | A |
| 4 | 5 | A |
| 4 | 11 | B |
| 4 | 21 | A |
| 5 | 5 | A |
| 5 | 11 | B |
| 5 | 21 | A |
| 6 | 5 | A |
| 6 | 11 | B |
| 6 | 21 | A |
+--------+---------+------+
// Desired Result
+---------+----------+
| SquadID | TeamMate |
+---------+----------+
| 5 | 6 |
| 7 | 0 |
| 11 | 3 |
| 21 | 6 |
+----------+---------+
我尝试使用子查询来指定要与之比较的特定玩家,并且由于该子查询具有多行,因此我使用了
in
而不是=
。// Current Query
SELECT
SquadID,
COUNT(Team IN (SELECT Team FROM selections WHERE SquadID=21) AND GameID IN (SELECT GameID FROM selections WHERE SquadID=21)) AS TeamMate
FROM
selections
GROUP BY
SquadID;
我得到的结果是用户玩过的游戏数量,而不是用户与
SquadID=21
处于同一团队的游戏数量// Current Result
+---------+----------+
| SquadID | TeamMate |
+---------+----------+
| 5 | 6 |
| 7 | 3 |
| 11 | 6 |
| 21 | 6 |
+---------+----------+
我想念什么?
// DESCRIBE selections;
+---------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------+------+-----+---------+-------+
| GameID | int(11) | NO | PRI | 0 | |
| SquadID | int(4) | NO | PRI | NULL | |
| Team | char(1) | NO | | NULL | |
| TeamID | int(11) | NO | | 1 | |
+---------+---------+------+-----+---------+-------+
最佳答案
一般规则是避免嵌套选择,并寻找逻辑上安排联接的更好方法。让我们看一下交叉连接:
From selections s1
inner join selects s2 on s1.gameid = s2.gameid and s1.team = s2.team
这将生成与另一个squadID参与的每个squadID的交叉联接列表(即,他们在同一场比赛和同一支球队中)。我们只对小队参加小队21的时间感兴趣,因此添加一个where子句:
where s2.squadid = 21
然后,只需选择所需的字段/计数:
select s1.squad, count(1) as teammate
任何集合需要一个分组
group by s1.squad
将其组合在一起然后试一试。奇怪的是,这将产生一个列表,其中21队将在自己的球队中出场6次。添加where子句可以消除这种情况
where s1.squadid <> s2.squadid
关于mysql - 将所有数据与专门选择的用户ID的数据进行比较?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46474925/