【问题标题】:mySQL SELECT join, group by or somethingmySQL SELECT join, group by 什么的
【发布时间】:2009-12-12 14:01:10
【问题描述】:

我无法走上正轨,任何帮助将不胜感激

我有一张桌子

+---+----------+---------+-----------+
|id | match_id | team_id | player_id |
+---+----------+---------+-----------+
| 1 |        9 |      10 |         5 |
| 2 |        9 |      10 |         7 |
| 3 |        9 |      10 |         9 |
| 4 |        9 |      11 |        12 |
| 5 |        9 |      11 |        15 |
| 6 |        9 |      11 |        18 |
+---+----------+---------+-----------+

我想用 match_id 上的 where 和两个团队 id 选择这些,所以输出将是

+---------+-------+------+---------+---------+
| MATCHID | TEAMA | TEAMB| PLAYERA | PLAYERB |
+---------+-------+------+---------+---------+    
|       9 |    10 |   11 |       5 |      12 |
|       9 |    10 |   11 |       7 |      15 |
|       9 |    10 |   11 |       9 |      18 |
+---------+-------+------+---------+---------+

这可能很简单,但我卡住了..

提前致谢

附言第一篇文章好像忘记写专栏了,抱歉

【问题讨论】:

  • 为什么玩家#5和玩家#12排成一排?您对此使用什么规则?
  • 是的。是什么决定了哪两个玩家在同一排?
  • 您应该重新考虑您的数据库设计。您最好使用一张将球队与比赛联系起来的表格和一张将球员与球队联系起来的表格。这将大大简化逻辑。
  • 5和12排成一排没关系,也可以是5和15或5和18

标签: sql mysql inner-join


【解决方案1】:

我认为你需要:

SELECT
    a.match_id, a.team_id AS TeamA, b.team_id AS teamB, 
    a.player_id AS PlayerA, b.player_id AS PlayerB
FROM PLayer AS a
    INNER JOIN Player AS b ON a.match_id = b.match_id
WHERE a.team_id < b.team_id

虽然这会给你每场比赛的每一对球员,即

+---------+-------+------+---------+---------+
| MATCHID | TEAMA | TEAMB| PLAYERA | PLAYERB |
+---------+-------+------+---------+---------+    
|       9 |    10 |   11 |       5 |      12 | 
|       9 |    10 |   11 |       5 |      15 |
|       9 |    10 |   11 |       5 |      18 |
|       9 |    10 |   11 |       7 |      12 |
|       9 |    10 |   11 |       7 |      15 |
|       9 |    10 |   11 |       7 |      18 |
|       9 |    10 |   11 |       9 |      12 |
|       9 |    10 |   11 |       9 |      15 |
|       9 |    10 |   11 |       9 |      18 |
+---------+-------+------+---------+---------+

为了进一步限制它,您需要一个标准来确定玩家应该配对。

【讨论】:

    【解决方案2】:

    我认为重新设计数据库会更好。

    【讨论】:

      【解决方案3】:
      select MatchA.id as MATCHID, MatchA.team_id as TEAMA, MatchB.team_id as TEAMB, MatchA.player_id as PLAYERA, MatchB.player_id as PLAYERB
      from Match as MatchA, match as MatchB 
      where MatchA.id = MatchB.id and MatchA.team_id < MatchB.team_id
      

      【讨论】:

      • 会给你 10 和 11 的团队,但也会给你 11 和 10 的团队。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-15
      • 2016-03-06
      • 2015-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多