我在 MySQL 实例中使用Lahman 棒球数据库。我想找到每年都在本垒打(HR)中名列前茅的球员。Batting 表的架构具有以下(相关部分):
+-----------+----------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+----------------------+------+-----+---------+-------+
| playerID | varchar(9) | NO | PRI | | |
| yearID | smallint(4) unsigned | NO | PRI | 0 | |
| HR | smallint(3) unsigned | YES | | NULL | |
+-----------+----------------------+------+-----+---------+-------+
对于每一年,每个玩家都有一个条目(每年数百到 12k,可以追溯到 1871 年)。一年内获得前 N 名击球手很容易:
SELECT playerID,yearID,HR
FROM Batting
WHERE yearID=2009
ORDER BY HR DESC LIMIT 3;
+-----------+--------+------+
| playerID | yearID | HR |
+-----------+--------+------+
| pujolal01 | 2009 | 47 |
| fieldpr01 | 2009 | 46 |
| howarry01 | 2009 | 45 |
+-----------+--------+------+
但我有兴趣找到每年的前三名。我找到了这样的解决方案,描述了如何从一个类别中选择顶部,我试图将它应用于我的问题,但最终得到一个永远不会返回的查询:
SELECT
b.yearID, b.playerID, b.HR
FROM
Batting AS b
LEFT JOIN
Batting b2
ON
(b.yearID=b2.yearID AND b.HR <= b2.HR)
GROUP BY b.yearID HAVING COUNT(*) <= 3;
我哪里出错了?