我有一张足球赛程表,每场比赛都有一个gameID和一个周数(weekNum)。我需要从每周获得最大游戏ID(基本上每周获得最后一个游戏)。
现在我正在使用它:
SELECT * FROM nflp_schedule WHERE gameID = (SELECT MAX(gameID) from nflp_schedule)
它拉开了最后一场比赛...但我不知道如何拉动每周的最后一场比赛。有什么想法吗?
答案 0 :(得分:0)
试试这个..我不是在mysql上所以无法测试,但这应该做到..
select *
from nflp_schedule a,
( SELECT weekNum, Max(gameID)
FROM nflp_schedule
) b
where a.gameID = b.gameID
答案 1 :(得分:0)
这将为您提供每周最多gameID
的所有周。返回的行将按weekNum
以升序方式排序。
SELECT weekNum, MAX(gameID) AS lastGameOfWeek
FROM nflp_schedule
GROUP BY weekNum
ORDER BY weekNum ASC
要根据上面派生的返回的gameID获取其他值,您需要选择子选择作为过滤条件或连接。
这可能看起来像这样(使用subselect):
SELECT gameID, weekNum, homeScore, visitorScore
FROM nflp_schedule
WHERE gameID IN (
SELECT MAX(gameID)
FROM nflp_schedule
GROUP BY weekNum
)
ORDER BY weekNum ASC
或者像这样(使用加入):
SELECT
n.gameID AS gameID,
n.weekNum AS weekNum,
n.homeScore AS homeScore,
n.visitorScore AS visitorScore
FROM nflp_schedule AS n
INNER JOIN (
SELECT MAX(gameID) AS maxGameID
FROM nflp_schedule
GROUP BY weekNum
) AS max
ON n.gameID = max.maxGameID
ORDER BY n.weekNum ASC
您将注意到,上面连接查询中使用的子选择看起来非常类似于之前示例中WHERE子句中直接使用的子选择。这实际上只是将子选择创建的“表”应用为主表上的过滤器的一种方法。您可能希望测试这两种方法,以查看在给定数据的情况下哪种方法执行得更快。