在 MySQL 中生成特定数量的行(不使用 table)

Generate a specific number of rows in MySQL (without using a table)

如何使用 SQL 查询生成定义数量的行——而不使用 table(这些行已经存在)?

例如,为了 return 3 行,我们可以这样做:

select * from (
    select 1 union all
    select 1 union all
    select 1
) t

结果如下:

1
1
1

但是,如果我需要 return,比方说,一千行,这是不切实际的。还有别的办法吗?

您可以使用:

WITH recursive numbers AS 
(  select 1 as Numbers
   union all
   select Numbers
   from numbers
   limit 1000
 )
select * from numbers;

根据需要更改限制。

另一种选择是:

WITH recursive numbers AS 
(  select 1 as Numbers
   union all
   select Numbers + 1
   from numbers
   where Numbers < 1000
 )
select * from numbers;

您可能需要将@@cte_max_recursion_depth增加到一个更大的值。

测试于

mysql> select version();
+-----------+
| version() |
+-----------+
| 8.0.25    |
+-----------+
1 row in set (0.00 sec)


mysql>     WITH recursive numbers AS
    ->     (  select 1 as Numbers
    ->        union all
    ->        select Numbers
    ->        from numbers
    ->        limit 100
    ->      )
    ->     select * from numbers;
+---------+
| Numbers |
+---------+
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
|    1 |
+------+
100 rows in set (0.00 sec)