简体   繁体   English

通过选择语句插入-oracle

[英]Insert by select statement -oracle

I was just trying to copy the values of one column into an empty column of another table . 我只是试图将一列的值复制到另一张表的空列中。 The two tables are students and payments . 这两个表是studentspayments Students have two columns : 学生有两列:

  • rno - primary key of number type // i filled it with some entries rno-数字类型的主键// i filled it with some entries

  • amount //this is completely empty 数量//this is completely empty

payments also have same no of columns : 付款也有相同的栏数:

  • rno - foreign key referencing rno of students table rno-引用学生表rno的外键

  • amount //this is FILLED 数量//this is FILLED

Now to copy amounts column from payments to students , i tried this command 现在要将付款中的 amounts列复制到学生,我尝试了此命令

insert into students(amount) select amount from payments ;

now normally this command works like a charm ,but here it is behaving slightly different . 现在,此命令通常像超级按钮一样工作,但是在这里它的表现略有不同。 It throws an error that NULL values cannot be inserted into students.rno 它将引发错误, NULL values cannot be inserted into students.rno

I tried reasoning that maybe its due to different number of entries inserted in two tables , but on eqalizing the no . 我尝试推理,也许是由于在两个表中插入的条目数量不同,但是使no相等。 of entries in both the tables , just the same result . 两个表中的项的总和,结果相同。

So the question is that how can i copy in such a situation ? 所以问题是,在这种情况下如何复制

Not quite clear on your requirements, but this will populate the STUDENTS table with the SUM of matching payments in the PAYMENTS table. 您的要求不太清楚,但这会在PAYMENTS表中用匹配付款的总和填充STUDENTS表。 Is this what you're after? 这是你所追求的吗?

UPDATE STUDENTS
SET    AMOUNT = (SELECT SUM(PAYMENTS.AMOUNTS)
                 FROM   PAYMENTS
                 WHERE  PAYMENTS.RNO = STUDENTS.RNO);

You don't want to add records to the students table (which is what INSERT does) you want to UPDATE existing records. 您不想将记录添加到Student表(这是INSERT所做的),而您想UPDATE现有记录。

I am not very familiar with Oracle syntax, but I adapted the answer to this question Update statement with inner join on Oracle to hopefully meet your needs. 我对Oracle语法不是很熟悉,但是我通过在Oracle上进行内部联接对这个问题Update语句的答案进行了调整,以期满足您的需求。

UPDATE students
SET    students.amount = (SELECT payments.amount
                          FROM   payments
                          WHERE  students.rno = payments.rno)  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM