mySQL SELECT join,group by或者什么

时间:2009-12-12 14:01:11

标签: sql mysql inner-join

我无法与此相提并论,任何帮助都将受到赞赏

我有一张桌子

+---+----------+---------+-----------+
|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 |
+---------+-------+------+---------+---------+

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

提前致谢

P.S。似乎在我的第一篇文章中忘了一栏,抱歉

3 个答案:

答案 0 :(得分:2)

我认为你需要:

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 |
+---------+-------+------+---------+---------+

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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