You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MySQL 8.0.41中WITH语句与INSERT INTO结合使用报错咨询

MySQL 8.0中WITH与INSERT INTO结合的语法错误原因及解决方法

错误原因

你遇到的1064语法错误,核心原因是MySQL对CTE(WITH子句)的语法位置有严格要求:WITH子句必须直接关联到后续的SELECT查询,不能作为独立前缀直接跟在INSERT INTO语句之前。你的写法中,WITH定义后直接接INSERT INTO,MySQL无法识别这种结构,因此抛出语法错误。

解决方法

有两种合法的写法可以实现需求:

写法一:将WITH子句放在INSERT INTO之后、SELECT之前

把WITH子句作为SELECT查询的前缀,放在INSERT INTO目标表定义之后:

drop table if exists testdb.with_insert_into;
create table testdb.with_insert_into (id int);

insert into testdb.with_insert_into (id)
with test_data as
(select 3 id)
select * from test_data;

写法二:用括号包裹带WITH的SELECT查询

将包含WITH子句的SELECT查询用括号包裹,作为INSERT的数据源:

drop table if exists testdb.with_insert_into;
create table testdb.with_insert_into (id int);

with test_data as
(select 3 id)
insert into testdb.with_insert_into (id)
(select * from test_data);

这两种写法都符合MySQL 8.0的语法规范,能够正常执行数据插入操作。

内容的提问来源于stack exchange,提问作者principal-ideal-domain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 11:34:50