问题描述
|
我设置了这一行:
ID player_id team_id created
1 2 1 2011-05-03 19:07:03
2 3 1 2011-05-05 12:13:18
3 2 5 2011-05-07 18:12:54
我会选择属于team_id = 1的玩家,但是我想从此结果中删除player_id = 2,因为该玩家实际上已经移动并且他在第5队中比赛(在team_id = 1中没有更多)。因此,最终结果将是:
ID player_id team_id created
2 3 1 2011-05-05 12:13:18
如何编写查询来做到这一点?我可以在单个查询中编写它吗?怎么样?
问候
解决方法
基本上,您可以从选择曾经加入团队的每个人开始,然后删除在为该团队输入之后为另一个团队创建条目的任何人。该查询专门允许您仅在一个位置更改
team_id
,并且如果您要检查多个团队,则可以得到正确的结果。
SELECT
t1.*
FROM
my_table t1
WHERE
t1.team_id = 1
AND
NOT EXISTS(
SELECT
t2.id
FROM
my_table t2
WHERE
t2.player_id = t1.player_id
AND
t2.team_id != t1.team_id
AND
t2.created > t1.created);
, 有一点像:
SELECT allData.ID,allData.player_Id,allData.team_Id
FROM myTable allData
JOIN
(SELECT
player_id,MAX(created) AS newestTime
FROM myTable
GROUP BY player_id) mostRecent
ON allData.player_id = mostRecent.player_id
AND allData.created = mostRecent.newestTime
WHERE team_id = 1