从匹配标准的子查询返回单个结果

时间:2018-04-19 16:06:24

标签: mysql

我有一个MySQL数据库,可存储足球运动员,赛程以及参与者所涉及的装置的详细信息。

我需要创建一个查询,返回所有玩家的列表以及玩家参与的最后一个装置的详细信息,但我无法理解这一点。

数据库表看起来像这样(我删除了不必要的字段);

players (stores details of players)
-------
id : int
name : text
team_id : int

fixtures (stores details of fixture)
-------
id : int
period : text
date : datetime

fixture_players (records which players were involved in which fixtures)
---------------
id : int
player_id : int
fixture_id : int

最新的灯具是此查询的第一个结果

"SELECT * FROM fixtures WHERE period = 'FullTime' ORDER BY date DESC LIMIT 1"

如何创建一个将这三个表合并在一起的查询,返回播放器和灯具细节,但每个播放器只有一个灯具,那个灯具是玩家参与的最后一个灯具?

1 个答案:

答案 0 :(得分:1)

您需要使用子查询来为您提供玩家所玩的最后一个装置。像这样:

SELECT p.name, f.period, f.date
FROM fixture_players fp 
JOIN fixtures f on fp.fixture_id = f.id
JOIN ( --Subquery: Last fixture dates played by players
    SELECT fp2.player_id, max(f2.date) lastFixDate 
    FROM fixture_players fp2 join fixtures f2 on fp2.fixture_id = f2.id 
    GROUP BY fp2.player_id --By grouoping player id we can have only one date per player
) a ON a.player_id = fp.player_id and a.lastFixDate = f.date
JOIN players p ON fp.player_id = p.id
GROUP BY p.id