我正在与棒球相关的网站上工作。我有一个桌子,有两个棒球队的击球阵容:
+----+----------+--------------+--------+
| id | playerId | battingOrder | active |
+----+----------+--------------+--------+
击球顺序是1到20之间的整数。这对应于以下逻辑:
活动字段为tinyint 0或1,表示土墩上的投手和盘子上的击球手。
已知事实:一支球队总会有一名主动投手,对方球队将有一名主动投手。
我需要编写一个查询,为主队球员返回一个对应于battingOrder中 next 击球手的行。 (在活跃击球手的击球命令后发生的那个)
示例:
之前我从未使用CASE查询,但我想出了以下内容:
SELECT *
FROM lineups
WHERE battingOrder =
CASE (
SELECT battingOrder
FROM lineups
WHERE battingOrder > 10 AND active = 1
LIMIT 1
)
WHEN 11 THEN 12
WHEN 12 THEN 13
WHEN 13 THEN 14
WHEN 14 THEN 15
WHEN 15 THEN 16
WHEN 16 THEN 17
WHEN 17 THEN 18
WHEN 18 THEN 19
WHEN 19 THEN 11
END
LIMIT 1;
它似乎有效,但我走进了什么边缘案例和/或陷阱?这有效吗?我特别感兴趣的是我的问题解决方案没有使用嵌套查询。
答案 0 :(得分:7)
Select LNext.player As NextPlayer
From lineups As L
Left Join lineups As LNext
On LNext.BattingOrder Between 11 And 20
And LNext.BattingOrder = Case
When L.BattingOrder = 19 Then 11
Else L.BattingOrder + 1
End
Where L.battingOrder Between 11 And 20
And L.active = 1
事实上,你可以让它像家一样处理:
Select LNext.player As NextPlayer
From lineups As L
Left Join lineups As LNext
On LNext.BattingOrder = Case
When L.BattingOrder = 19 Then 11
When L.BattingOrder = 9 Then 1
Else L.BattingOrder + 1
End
Where L.active = 1