Using RECURSIVE CTE with INSERT SELECT to generate table data with MariaDB

我与影子孤独终老i 提交于 2020-06-23 08:19:30

问题


I'm using Maria DB version 10.2.9 on windows 7,

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

I'm trying to use recursive CTE with INSERT SELECT to create some test Data. For simplicity follows below a single column table to be populated:

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

And the CTE which generates values 1 to 10:

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;

The above generates a syntax error. Note that if the insert line is removed then the 10 rows will appear as expected with values 1 to 10 from the SELECT statement.

Does anyone know restrictions concerning use of CTE in INSERT/SELECT queries, or any workaround?

Update : The following two queries work, both the one from @elenst reply and the one from provided the link in @PM 77 comment:

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;

The following is an adaptation from the link provided by @PM 77.

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:


There is no restriction here, you just need to do it the other way round syntax-wise:

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;

Update: to respond to the claim that it still causes the error, adding the actual client output:

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)


来源:https://stackoverflow.com/questions/48511376/using-recursive-cte-with-insert-select-to-generate-table-data-with-mariadb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!