在 MySQL 的选择查询中使用 CASE、WHEN、THEN、END

2022-01-23 00:00:00 select subquery mysql case-when

我正在开发一个与棒球相关的网站.我有一张桌子,上面有两支棒球队的击球阵容:

I'm working on a baseball related website. I have a table with a batting lineup for two baseball teams:

+----+----------+--------------+--------+
| id | playerId | battingOrder | active |
+----+----------+--------------+--------+

击球顺序是1到20之间的整数,对应如下逻辑:

Batting order is an integer between 1 and 20. This corresponds to the following logic:

  1. 击球顺序 1-9 —客队阵容
  2. 击球顺序 10 -客队投手
  3. 击球顺序 11-19 —主队阵容
  4. 击球顺序 20 -主队投手

active 字段是一个 tinyint 0 或 1,代表投手在土墩上,击球手在盘子上.

The active field is a tinyint 0 or 1, representing the pitcher on the mound and the batter on the plate.

已知事实:总会有一名来自一支球队的现役投手和一名来自对方球队的现役击球手.

Known Fact: There will always be one active pitcher from one team and one active batter from the opposite team.

我需要编写一个查询,返回与 battingOrder 中的 下一个 击球手相对应的主队球员的行.(发生在 主动击球手的 battingOrder 之后的那个)

I need to write a query that returns a row for a home team player that corresponds to the next batter in the battingOrder. (the one that that occurs after the active batter's battingOrder)

例子:

  1. 如果 battingOrder 13 中的玩家处于活动状态,则查询应返回击球顺序为 14 的玩家.
  2. 如果 battingOrder 19 中的球员处于活动状态,则查询应返回击球顺序为 11 的球员(阵容循环回到球队的第一个球员).

我以前从未使用过 CASE 查询,但我想出了以下内容:

I've never used a CASE query before, but I came up with the following:

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;

这似乎可行,但我遇到了哪些极端情况和/或陷阱?这有效率吗?我对不使用嵌套查询的问题的解决方案特别感兴趣.

It seems to work, but what edge cases and/or pitfalls have I walked into? Is this efficient? I'm particulary interested in a solution to my problem that does not use a nested query.

推荐答案

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

事实上,你可以让它像这样处理家庭和外出:

In fact, you could make it handle both home and away like so:

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

相关文章