我正在制作一个程序,根据具有两个属性得分的最高总和的人自动建议选择哪个玩家,例如,得分和等级。目标得救。因此,我有一个表(玩家),看起来像这样:
+---------------+--------------+-------------+
| Name | GoalsScored | GoalsSaved |
+---------------+--------------+-------------+
| John Smith | 15 | 12 |
| John Doe | 12 | 20 |
| Bob John | 7 | 6 |
| John Bob | 10 | 30 |
| Bobby Johnson | 25 | 30 |
+---------------+--------------+-------------+
一个临时表来存储已经选择的玩家(taken_players)的名字,看起来像这样:
+-----------------+
| takenplayername |
+-----------------+
| Bob John |
| Bobby Johnson |
+-----------------+
我正在寻找返回具有最高GoalsScored + GoalsSaved的玩家名称的SQL查询,只要该玩家未列在所拍摄玩家的表中。
SELECT * FROM players
LEFT JOIN taken_players ON players.Name = taken_players.takenplayername
WHERE taken_players.takenplayername IS NULL
AND GoalsScored, GoalsSaved in (
SELECT MAX(GoalsScored + GoalsSaved)
FROM players
)
到目前为止,我有上面的代码,只能部分工作。我遇到的问题是
GoalsScored, GoalsSaved in (SELECT MAX(GoalsScored + GoalsSaved)
声明的一部分没有做我需要的,我在这里猜测一些代码来说明我希望它为此问题的目的做什么。
另一个问题是,如果将最佳玩家添加到所选玩家列表中,则查询将返回任何内容而不是下一个最佳玩家。
我对此很新,任何帮助都将不胜感激。
答案 0 :(得分:0)
您希望order by
和某些内容限制为一行:
SELECT p.*
FROM players p LEFT JOIN
taken_players tp
ON p.Name = tp.takenplayername
WHERE tp.takenplayername IS NULL
ORDER BY (GoalsScored + GoalsSaved) DESC
LIMIT 1;
LIMIT 1
可能是其他一些因素,具体取决于数据库:
SELECT TOP 1
WHERE rownum = 1
FETCH FIRST 1 ROW ONLY
答案 1 :(得分:0)
问题是你的WHERE子句。它将选择最大总和,但它不与特定玩家绑定。解决这个问题的方法之一:
SELECT p.* FROM players p
LEFT JOIN taken_players t ON p.Name = t.takenplayername
WHERE t.takenplayername IS NULL
AND (p.GoalsScored + p.GoalsSaved) = (SELECT MAX(GoalsScored + GoalsSaved) as MaxScore FROM players)
注意:如果多个玩家获得最高分(如果是平局),此查询将返回多个记录
答案 2 :(得分:0)
SELECT * from players p where p.id not in (SELECT id from taken_players) and (p.GoalsScored + p.GoalsSaved) = (SELECT MAX(GoalsScored + GoalsSaved) as MaxScore FROM players)
与上述答案类似,它可能会为您提供多个玩家。只获得一个玩家的语法因DBMS而异,但这在大多数情况下都有效。
SELECT * FROM Players where id = (SELECT MIN(id) from players where players.id NOT in (SELECT id from taken_players) and players.GoalsScored+ players.GoalsSaved = (SELECT MAX(players.GoalsScored+ players.GoalsSaved from players where players.id not in (SELECT id from taken_players))