【问题标题】:Insert into table using common table express result [duplicate]使用公用表快速结果插入表[重复]
【发布时间】:2020-04-30 18:24:44
【问题描述】:

我正在练习 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 秒处的“插入销售(id,first_name,last_name,age,data_of_age)选择 id,first_name”附近使用正确的语法

【问题讨论】:

  • 有什么特别的原因不分享确切的错误信息,这样我们就不必猜测它发生在哪里?
  • 当您就语法错误寻求帮助时,请发布准确且完整的错误消息。不要让我们猜测!
  • 好点,我已经用语法错误代码更新了问题。感谢您的快速回复。错误代码:1064。您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 7 行 0.000 秒处的“插入销售(id、first_name、last_name、age、data_of_age)选择 id、first_name”附近使用正确的语法

标签: mysql sql mysql-error-1064


【解决方案1】:

您应该在 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;

【讨论】:

  • 哦,我明白了,非常感谢。刚接触 SQL,所以我觉得有些东西我不理解。
猜你喜欢
  • 1970-01-01
  • 2017-06-16
  • 2011-12-25
  • 2015-03-20
  • 2011-08-27
  • 2016-06-08
  • 2021-01-31
  • 2019-02-10
  • 1970-01-01
相关资源
最近更新 更多