SQL让那些在团队中连续玩了3年的玩家

时间:2017-10-20 21:50:38

标签: mysql

我是使用MySQL的新手,我不得不写一个我必须写的查询。鉴于美国职业棒球大联盟中的棒球运动员数据库及其所有统计数据,我需要编写一个查询,以显示哪些球员在波士顿红袜棒球队至少连续3年出场。这就是我到目前为止所拥有的:

SELECT player.nameFirst, player.nameLast
FROM player
WHERE (...something something...) >= 3
AND player.teamID = "Boston Red Sox"

除了播放器表之外,还有另一个名为appear的表,其中包含playerID,然后是他们为团队所玩的年份。出现的表格还有其他信息,例如该季节的统计数据。例如,如果一名球员为红袜队效力了4年,我们会在看似表格中看到四行,每一行都有一个整数,表示他们在该队伍中的哪一年。

我知道在查询变得复杂之后,我不确定如何首先关闭,计算玩家在团队中的年数,更不用说如何知道这些年份是连续的还是不。谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

加入appears表格两次以查找相关年份的出场次数。

SELECT DISTINCT a1.playerID
FROM appears AS a1
JOIN appears AS a2 ON a1.playerID = a2.playerID AND a1.year = a2.year-1
JOIN appears AS a3 ON a1.playerID = a3.playerID AND a1.year = a3.year-2

您可以将此子查询与原始查询一起加入,以获取有关这些玩家的其他信息。

DISTINCT确保我们只返回玩家ID一次,即使他们连续玩了3年以上。

答案 1 :(得分:1)

按照@ Barmar的说明,您的查询应如下所示:

SELECT DISTINCT player.nameFirst, player.nameLast
FROM player
INNER JOIN (
    SELECT DISTINCT a1.playerID
    FROM appears AS a1
    JOIN appears AS a2 ON a1.year = a2.year-1
    JOIN appears AS a3 ON a1.year = a3.year-2
) AS ap ON player.playerID = ap.playerID
WHERE player.teamID = "Boston Red Sox"