MySQL CTE - 是否可以遍历数字范围?

MySQL CTE - is it possible to iterate over range of numbers?

我很好奇是否可以使用 CTE 进行类似的查询("id" 的值可能会有所不同,不一定是连续的)

SELECT
      elt((@mxId := if(@mxId + 1 <= 3, @mxId + 1, 1)), 5, 10, 22, 33) val,
      id
   FROM my_table
   INNER JOIN (SELECT @mxId := 0) tmp;

预期输出:

 val | id
-----+----
5    | 1
10   | 2
22   | 3
5    | 4
10   | 5
22   | 6
5    | 7
10   | 8
22   | 9
5    | 10
10   | 11
22   | 12
5    | 13
10   | 14
22   | 15
5    | 16
10   | 17
22   | 18
5    | 19
10   | 20

with my_table_numbered as (
  select ((row_number() over ())-1)%3 as rn_mod, id from my_table
)
select elt(rn_mod+1, 5, 10, 22, 33) as val, id 
from my_table_numbered;

输出:

+------+----+
| val  | id |
+------+----+
| 5    |  1 |
| 10   |  2 |
| 22   |  3 |
| 5    |  4 |
| 10   |  6 |
| 22   |  7 |
| 5    |  8 |
| 10   |  9 |
| 22   | 13 |
| 5    | 14 |
| 10   | 15 |
| 22   | 16 |
+------+----+

您应该在 CTE 中指定一个 ORDER BY 以获得有意义且可靠的行编号,但您在问题的查询中没有。

row_number() OVER ()

这很神奇 - 非常感谢