我在查询时返回播放器的id
,name
以及玩家的第一个匹配date
,matchid
和{{1} }。
我想要玩家最后一场比赛的相同信息。
opponent
其中`players`
id | name
1 | playername10
2 | playername22
3 | playername33
4 | playername45
5 | playername55
`matches`
id | gamedate | opponent
1 | 2011-01-01 | opponent1
2 | 2011-01-02 | opponent2
3 | 2011-01-03 | opponent3
4 | 2011-01-04 | opponent4
5 | 2011-01-05 | opponent5
`playermatchscores`
id | matchid | player | goals
1 | 1 | playername10 | 1
2 | 1 | playername22 | 2
3 | 2 | playername10 | 1
4 | 1 | playername33 | 1
5 | 3 | playername45 | 2
6 | 4 | playername55 | 1
7 | 2 | playername55 | 1
8 | 3 | playername22 | 2
9 | 5 | playername55 | 1
是表matchid
中id
的外键。
我尝试了几个查询,但我可能会以错误的方式接近它。我怎样才能找到获取所需信息的方法?
答案 0 :(得分:0)
关于LEFT JOIN的信息:http://www.w3schools.com/sql/sql_join_left.asp
SELECT players.id, MAX(matches.gamedate) AS first_match, MIN(matches.gamedate) AS last_match
FROM playermatchscores
LEFT JOIN players ON players.player = playermatchscores.player
LEFT JOIN matches ON matches.id = playermatchscores.matchid
GROUP BY players.player
我没有测试过这个选择。
P.S。你应该在playermatchscores中使用player_id的外键给玩家表。
问题发生变化后:
SELECT players.*, matches.*,
FROM playermatchscores
LEFT JOIN players ON players.name = playermatchscores.player
LEFT JOIN matches ON matches.id = playermatchscores.matchid
ORDER BY matches.gamedate ASC
WHERE players.id = 3
LIMIT 1
对于最后一场比赛,将ASC替换为DESC。
P.S。这不是最好的方法,但它应该有效。