使用带有INSERT SELECT的RECURSIVE CTE通过MariaDB生成表数据

时间:2018-01-29 22:55:44

标签: mariadb common-table-expression

我在Windows 7上使用Maria DB版本10.2.9,

MariaDB > select @@version;
+----------------+
| @@version      |
+----------------+
| 10.2.9-MariaDB |
+----------------+

我正在尝试使用带有INSERT SELECT的递归CTE来创建一些测试数据。为简单起见,下面是要填充的单个列表:

CREATE TABLE cte_populated
(
  id INT NOT NULL PRIMARY KEY
)
  ENGINE = InnoDB;

生成值1到10的CTE:

WITH  RECURSIVE int_seq AS (
SELECT 1 AS val
UNION ALL
SELECT val + 1
FROM int_seq
WHERE val  < 10
)
INSERT cte_populated(id)
SELECT int_seq.val FROM int_seq;

以上生成语法错误。 请注意,如果删除了插入行,那么10行将按预期显示,SELECT语句中的值为1到10.

有没有人知道在INSERT / SELECT查询中使用CTE的限制,还是有任何解决方法?

更新: 以下两个查询都有效,包括来自@elenst回复的查询和来自@PM 77注释中的链接的查询:

INSERT cte_populated(id)
WITH  RECURSIVE int_seq AS (
SELECT 1 AS val
UNION ALL
SELECT val + 1
FROM int_seq
WHERE val  < 10)
SELECT int_seq.val as id FROM int_seq;

以下是@PM 77提供的link改编。

INSERT INTO cte_populated
WITH  RECURSIVE int_seq(val) AS (
SELECT 1
UNION ALL
SELECT 1 + val FROM int_seq WHERE val  < 10)
SELECT * FROM int_seq;

1 个答案:

答案 0 :(得分:2)

这里没有限制,你只需要在语法方面做其他方式:

INSERT cte_populated(id)
WITH  RECURSIVE int_seq AS (
SELECT 1 AS val
UNION ALL
SELECT val + 1
FROM int_seq
WHERE val  < 10
)
SELECT int_seq.val FROM int_seq;

更新:响应声称它仍会导致错误,添加实际的客户端输出:

MariaDB [test]> CREATE TABLE `cte_populated` (
    ->   `id` int(11) DEFAULT NULL
    -> ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Query OK, 0 rows affected (0.21 sec)

MariaDB [test]> INSERT cte_populated(id)
    -> WITH  RECURSIVE int_seq AS (
    -> SELECT 1 AS val
    -> UNION ALL
    -> SELECT val + 1
    -> FROM int_seq
    -> WHERE val  < 10)
    -> SELECT int_seq.val as id FROM int_seq;
Query OK, 10 rows affected (0.04 sec)
Records: 10  Duplicates: 0  Warnings: 0

MariaDB [test]> SELECT * FROM cte_populated;
+------+
| id   |
+------+
|    1 |
|    2 |
|    3 |
|    4 |
|    5 |
|    6 |
|    7 |
|    8 |
|    9 |
|   10 |
+------+
10 rows in set (0.00 sec)

MariaDB [test]> select @@version;
+----------------+
| @@version      |
+----------------+
| 10.2.9-MariaDB |
+----------------+
1 row in set (0.00 sec)