使用 select 语句在表中插入

Posted

技术标签:

【中文标题】使用 select 语句在表中插入【英文标题】:insertion in a table using select statement 【发布时间】:2013-03-21 21:21:45 【问题描述】:

您好,我正在使用 select 语句将值插入到表中。但是插入没有发生。 select语句的结果集中有5行。但是当我使用选择数据触发插入语句时,不会将其插入表中。

我检查了属性的顺序,一切似乎都是正确的。我还尝试使用“values”关键字在表中插入一行,并在此帮助下插入数据。 为什么我的插入不能使用“选择”命令?

请帮帮忙。

下面是查询

insert into schema1.tabletemp
    select distinct 
    a.name as name,
    a.stu_number as rollno,
    c.userid as login_id,
    b.Address as stuAddress,
    b.totalgrades as FinalGrdaes
    ' ' as Misc
from
    Schema1.stu_info a, schema1.address_info b, schema1.logindetails c
where
    a.stu_no = b.record_no and
    a.status in ('Active') and 
   c.last_name=a.stu_lname and 
    c.first_name=a.stu_fname and  
    a.stu_no not in (select distinct student_number from schema1.student_final_records);

此查询正在尝试将学生数据插入 tabletemp。条件是不应该再次插入 student_final_record 表中存在的学生记录。因此,系统中的任何新学生编号(即 student_final_record 中不存在的学生编号)都将插入到 tabletemp 中。

不在不工作的条款中。有什么建议吗????

【问题讨论】:

请分享您的 DDL、示例数据并插入查询 向我们展示您的 sql,也许我们可以提供帮助。 在 INSERT...SELECT 之后是否执行了 COMMIT 语句? 插入 schema1.tabletemp 选择不同的 a.name 作为名称,a.stu_number 作为 rollno,c.userid 作为 login_id,b.Address 作为 stuAddress,b.totalgrades 作为 FinalGrdaes ''作为来自 Schema1 的 Misc .stu_info a, schema1.address_info b, schema1.logindetails c 其中 a.stu_no = b.record_no and a.status in ('Active') and c.last_name=a.stu_lname and c.first_name=a.stu_fname and a. stu_no 不在(从 schema1.student_final_records 中选择不同的 student_number); 【参考方案1】:

这里少了一个逗号:

   b.totalgrades as FinalGrdaes
    ' ' as Misc

固定版本:

   b.totalgrades as FinalGrdaes,
    ' ' as Misc

【讨论】:

谢谢我更正了。我正在使用带有插入语句的提交,但现在它一直在插入相同的行。我检查了查询中“NOT IN”子句的使用,它不起作用。每次我触发此查询时,它都会返回相同的行。 select a.stu_no from schema1.tabletemp a where a.stu_no not in (select student_number from schema2.student_final_record); 谢谢我更正了。我正在使用带有插入语句的提交,但现在它一直在插入相同的行。我检查了查询中“NOT IN”子句的使用,它不起作用。每次我触发此查询时,它都会返回相同的行。 select a.stu_no from schema1.tabletemp a where a.stu_no not in (select student_number from schema2.student_final_record);我不确定这个查询是否正确。请看看,让我知道 您的 NOT IN 子句针对的是未包含在查询中的表,因此您所做的任何操作都不会更改此查询将返回的值。 嗨,大卫,我是否应该在主查询中也包含子查询中使用的表

以上是关于使用 select 语句在表中插入的主要内容,如果未能解决你的问题,请参考以下文章

SQL 在表中插入

如果插入语句给出重复键异常(在表中找到行 id=1)如何更新 JDBC(Postgresql)中的语句

从 SQL SELECT 语句中获取值,即使它在表中不存在

SQL动态SELECT语句来自存储在表中的值

使用 SELECT 和 JOIN 语句将多个数据插入表中

SQLite - 在 SELECT INTO 语句上生成 GUID/UUID