从 CTE 插入 table

Insert into table from CTE

我试图将数据从 master_data table 插入 tpl_transferred_debtor table。由于 tpl_transferred_debtor 有主键 tpl_code,我需要使用 CTE 来处理来自 master_data 插入前。

with distinct_object_code_id as (
    select MIN(id) as id
    from master_data
    where original_type = 'tpl'
    group by object_code
), 
tmp_tpl_table as (
    select 
        md.accounting_id as accounting_id, 
        md.object_code as object_code,
        md.name as name,
        md.created_at as created_at,
        md.updated_at as updated_at
    from master_data md
    join distinct_object_code_id using(id)
)
insert into tpl_transferred_debtor (debtor_id, tpl_code, status, description, created_at, updated_at)
select 
    tmp.accounting_id, 
    tmp.object_code, 
    'active', 
    tmp.name, 
    tmp.created_at, 
    tmp.updated_at
from tmp_tpl_table tmp;

它给出了这个错误

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'insert into tpl_transferred_debtor (debtor_id, tpl_code, status, description, cr' at line 17

我通过删除 insert into 行检查了 CTE table tmp_tpl_table,它工作正常。

with distinct_object_code_id as (
    select MIN(id) as id
    from master_data
    where original_type = 'tpl'
    group by object_code
), 
tmp_tpl_table as (
    select 
        md.accounting_id as accounting_id, 
        md.object_code as object_code,
        md.name as name,
        md.created_at as created_at,
        md.updated_at as updated_at
    from master_data md
    join distinct_object_code_id using(id)
)
select 
    tmp.accounting_id, 
    tmp.object_code, 
    'active', 
    tmp.name, 
    tmp.created_at, 
    tmp.updated_at
from tmp_tpl_table tmp;

如果我不用CTE处理数据,写一个简单的insert into ... select就可以了

insert into tpl_transferred_debtor (debtor_id, tpl_code, status, description, created_at, updated_at)
select 
    tmp.accounting_id, 
    tmp.object_code, 
    'active', 
    tmp.name , 
    tmp.created_at, 
    tmp.updated_at
from master_data tmp
where tmp.original_type = 'tpl';

我做错了什么?

编辑:MYSQL数据库版本为8.0.29-0ubuntu0.20.04.3.

试试这个语法:

INSERT INTO tmp( tmp_id )
  WITH cte AS (
    SELECT 1 AS tmp_id FROM dual
  )
  SELECT tmp_id
  FROM cte;

https://dev.mysql.com/doc/refman/8.0/en/with.html