如何使用内部联接在表中插入值?

时间:2018-02-03 06:08:47

标签: oracle

我正在尝试使用以下查询将数据插入table1.col1。

INSERT INTO table1 t1( t1.col1)  
SELECT t2.col1
FROM table2 t2
WHERE t1.col2= t2.col2;

显然,它不起作用(可能是有缺陷的逻辑)。我怎样才能达到类似的效果。 如果我没有意义,请告诉我。

4 个答案:

答案 0 :(得分:1)

INSERT INTO table1(col1)
SELECT t2.col1 FROM table2 t2 INNER JOIN table1 t1 on t1.col2 = t2.col2;

答案 1 :(得分:0)

INSERT INTO table1(col1)
SELECT t2.col1 FROM table1 t1,table2 t2 在哪里t1.col2 = t2.col2;

答案 2 :(得分:0)

It seems you need a MERGE statement with MATCHED(for already existing rows in table1) and
NOT MATCHED(for rows not inserted into table1 yet) options :

MERGE INTO table1 t1
  USING table2 t2
    ON (t1.col2 = t2.col2)
  WHEN MATCHED THEN
    UPDATE SET t1.col1 = t2.col1
  WHEN NOT MATCHED THEN
    INSERT (col1,col2)
    VALUES (t2.col1, t2.col2);

Demo

答案 3 :(得分:0)

So, I was not looking to insert but to update...stupid question I know :) This is what I was looking for.

update table1 t1 set t1.col1 = (select t2.col1 from table2 t2 where t1.col2 = t2.col2);