使用普通 table 表达结果插入 table

Insert into table using common table express result

我正在练习 SQL 并尝试获取最后一条记录并添加一条递增年份和 ID 的新记录。我知道这可以更容易地完成,但我正在尝试了解如何使用 CTE。先感谢您。

我遇到语法错误。使用 MySQL 8.0

WITH cte_0 (id,first_name,last_name,age,date_of_age) as (
select * from sales order by age desc limit 1
), 
cte_1 (id,first_name,last_name,age,data_of_age) as (
select id + 1 as id,first_name,last_name,age +1 as age, DATE_ADD(date_of_age ,INTERVAL 1 YEAR) as data_of_age from cte_0
)
insert into sales (id,first_name,last_name,age,data_of_age) select id,first_name,last_name,age,data_of_age from cte_1
;

语法错误: 错误代码:1064。您的 SQL 语法有误;查看与您的 MySQL 服务器版本对应的手册,了解在第 7 行 0.000 sec

附近 'insert into sales (id,first_name,last_name,age,data_of_age) select id,first_name' 使用的正确语法

您应该在 INSERT 语句中使用 CTE:

insert into sales (id,first_name,last_name,age,data_of_age)
WITH cte_0 (id,first_name,last_name,age,date_of_age) as (
select * from sales order by age desc limit 1
), 
cte_1 (id,first_name,last_name,age,data_of_age) as (
select id + 1 as id,first_name,last_name,age +1 as age, DATE_ADD(date_of_age ,INTERVAL 1 YEAR) as data_of_age from cte_0
) 
select id,first_name,last_name,age,data_of_age from cte_1;