Mysql

我們可以在 MySQL 中使用 x AS ( … ) INSERT INTO y(k) SELECT * FROM x 嗎?

  • August 24, 2020

我們可以INSERT INTO SELECT,但是如果我有一堆WITH AS陳述(大約 27ish)SELECT呢?我目前的解決方案是進行查詢,然後使用程式語言進行掃描(Golang就我而言),然後使用普通INSERT INTO語句一一插入。有沒有一步解決方案來做到這一點?

就像是

insert into item
 with x as (    
   select id + 10 as id1, concat(brand,' D') as brand1 from item),
      y as (    
   select id + 20 as id1, concat(brand,' E') as brand1 from item)  
 select * from x   
 union all   
 select * from y

我們可以!

Ir 在一個級別上不允許有多個 WITH

你只能使用子查詢

INSERT INTO testable WITH
 cte1 AS (SELECT a, b FROM table1),
 cte2 AS (SELECT c, d FROM table2)
SELECT b, d FROM cte1 JOIN cte2
WHERE cte1.a = cte2.c;

但是您可以在不同級別使用 With 子句,例如

INSERT INTO testtabe WITH cte1 AS (SELECT 1)
SELECT * FROM (WITH cte2 AS (SELECT 2) SELECT * FROM cte2 JOIN cte1) AS dt;

引用自:https://dba.stackexchange.com/questions/274232