带分组的查询设计
我无法针对这种情况提出有效的查询...
表格:
[ matchID ] [ User ] [ team ]
1 10 1
1 77 2
2 10 1
2 77 1
3 10 2
4 10 1
注释:
- 有时对手是未知的,例如在比赛 2、3 和4
- 有时一个团队只有一个人,例如比赛 1
- 有时一个团队有 n 个人,例如比赛 2
期望的查询结果:
给定用户的 matchID 列表,其中对手未知。
我的第一次尝试是:
SELECT matchID FROM table
GROUP BY matchID
HAVING COUNT(matchID) = 1
但后来我意识到我没有统计有队友但对手未知的比赛,例如上面的比赛2。
用简单的英语来说,我需要获取所有 matchID,其中:
- 涉及给定用户 <- 编辑添加
- 每个人都在同一个团队中
- ,或者只列出一个人
,但我不知道如何在一个查询中有效地做到这一点。帮助?
I'm having trouble coming up with a working query for this situation...
Table:
[ matchID ] [ User ] [ team ]
1 10 1
1 77 2
2 10 1
2 77 1
3 10 2
4 10 1
Notes:
- sometimes the opponent is unknown, for example in matches 2, 3, and 4
- sometimes a team has only one person on a side, for example match 1
- sometimes a team has n persons on a side, for example match 2
Desired Query Results:
A list of matchIDs for a given user where the opponent is unknown.
My first attempt was:
SELECT matchID FROM table
GROUP BY matchID
HAVING COUNT(matchID) = 1
but then I realized that I wasn't counting matches where there are teammates but unknown opponents, such as match 2 above.
In plain English, I need to get all matchIDs where:
- involving a given user <- edited to add
- everyone is on the same team
- OR there is only one person listed
but I'm not sure how to do that efficiently in one query. Help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以计算每场比赛的球队数量。如果只有一个那就不够了:
You can count the number of teams per match. If there's only one then there's not enough:
您尚未提供表名称,因此我决定将其命名为
mut
作为 matches users team 的缩写。无论如何,这似乎适用于所有情况:you haven't provided a table name, so i have decided to call it
mut
as in short for matches users teams. anyways, this seems to be working on all cases:您似乎需要那些表中只记录了一支球队的比赛,并且此查询为您提供了这些比赛。
如果匹配必须涉及特定用户(示例数据为 10),那么:
您可以将其作为(内部)自连接来执行:
或者,也许更清楚一点:
子选择选择 UserID 10 的那些匹配玩过;其余的工作和以前一样。
You seem to need those matches where only one team is recorded in the table, and this query gives you those matches.
If the match must involve a specific user (10 for the sample data), then:
You can probably do that as an (inner) self-join:
Or, perhaps a little more clearly:
The sub-select picks those matches where UserID 10 played; the rest works as before.