我尝试将
master_data
表中的数据插入到 tpl_transferred_debtor
表中。由于 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
我通过删除
tmp_tpl_table
线检查了 CTE 表 insert into
,它工作正常。
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;
您似乎遇到了与 MySQL 中 CTE(公用表表达式)和后续 INSERT 语句的使用相关的语法问题。
在 MySQL 中,不能在 CTE 定义之后直接使用 INSERT 语句。为了克服这个问题,您需要将 INSERT 语句封装在另一个 SELECT 语句中。以下是修改查询的方法:
sql 复制代码 与distinct_object_code_id AS ( 选择 MIN(id) AS id 来自主数据 WHERE 原始类型 = 'tpl' 按对象代码分组 ), tmp_tpl_表 AS ( 选择 md.accounting_id AS 会计_id, md.object_code AS object_code, md.name AS 名称, md.created_at AS 创建的_at, md.updated_at AS update_at 来自master_data md 使用(id)连接distinct_object_code_id ) 插入 tpl_transferred_debtor(debtor_id、tpl_code、状态、描述、created_at、updated_at) 选择 tmp.accounting_id, tmp.object_code, '积极的', tmp.名称, tmp.created_at, tmp.updated_at 从 tmp_tpl_table tmp; 在此修改后的查询中,我将 INSERT 语句包装在附加的 SELECT 语句中,这是 MySQL 中此语法限制的常见解决方法。
这应该可以解决您面临的语法错误。